Conversion to number in JavaScript

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') );

Alternative

Often, the sign + is placed before the string instead of Number to shorten the code. Thus, an operation is performed on the string that is valid only for numbers, and the string is converted to a number.

See an example:

let a = +'2'; // the number 2 will be written to the variable let b = +'3'; // the number 3 will be written to the variable alert(a + b); // shows 5

Here is another example:

let a = '2'; let b = +a; // the number 2 will be written to b

And here is the following example, although working, but it does not look very nice. It would be more appropriate to use the function Number:

let a = '2'; let b = '3'; alert(+a + +b); // shows 5

Given a code:

let a = '2'; let b = '3'; alert(a + b); // shows '23'

Using the described above technique with a plus, correct the above code such a way that the variables a and b are assigned a number, not a string, and the result, respectively, would be not '23', but 5.

Not only numbers

When trying to convert a string containing not only numbers, but also other characters, the Number function will return the value NaN:

alert(Number('2s')); // shows NaN

The same effect will bring the use of plus:

alert(+'2s'); // shows NaN
enru