Let's consider the following code:
let a = '2';
let b = '3';
alert(a + b); // shows '23'
As you can see, in our case, both variables contain strings, and respectively, they add up like strings.
Suppose, we would like the values of our
variables in this case to be added not as strings,
but as numbers. In this case, we can force
our variable type to be converted to a number
using the special function Number
:
let a = '2';
let b = '3';
alert(Number(a) + Number(b)); // shows 5
You can convert strings to numbers not with the addition operation, but immediately when writing to a variable. This will work:
let a = Number('2'); // the number 2 will be written to the variable
let b = Number('3'); // the number 3 will be written to the variable
alert(a + b); // shows 5
Given a variable a
with the value
'10'
and a variable b
with
the value '20'
. Add the given
variables as numbers.
Without running the code, determine what will be displayed on the screen:
alert( Number('2') + Number('3') );
Without running the code, determine what will be displayed on the screen:
alert( 2 + Number('3') );
Without running the code, determine what will be displayed on the screen:
alert( '2' + Number('3') );