Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do I get 24 when adding 2 + 4 in javascript

Tags:

javascript

I am trying this:

function add_things() {
  var first = '2';
  var second = '4';
  alert(first + second);
}

But it gives me 24 instead of 6, what am I doing wrong?

like image 421
Tilendor Avatar asked Aug 03 '09 23:08

Tilendor


People also ask

How do you sum numbers in JavaScript?

const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.

How do you double a number in JavaScript?

numbers = [1,2,3,4,5]; function doubling(number) { number *= 2; return number; } obj = {}; for (var i = 0; i < numbers. length; i++) doubled = doubling(numbers[i]); obj[numbers[i]] = doubled; console. log(obj);

What is Number () in JavaScript?

Values of other types can be converted to numbers using the Number() function. The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to what it can store.


4 Answers

You're concatenating two strings with the + operator. Try either:

function add_things() {
  var first = 2;
  var second = 4;
  alert(first + second);
}

or

function add_things() {
  var first = '2';
  var second = '4';
  alert(parseInt(first, 10) + parseInt(second, 10));
}

or

function add_things() {
  var first = '2';
  var second = '4';
  alert(Number(first) + Number(second));
}

Note: the second is only really appropriate if you're getting strings from say a property or user input. If they're constants you're defining and you want to add them then define them as integers (as in the first example).

Also, as pointed out, octal is evil. parseInt('010') will actually come out as the number 8 (10 in octal is 8), hence specifying the radix of 10 is a good idea.

like image 129
cletus Avatar answered Nov 15 '22 19:11

cletus


Try this:

function add_things() {
  var first = 2;
  var second = 4;
  alert(first + second);
}

Note that I've removed the single quotes; first and second are now integers. In your original, they are strings (text).

like image 38
Ben M Avatar answered Nov 15 '22 21:11

Ben M


That is one of the "Bad Parts" of JavaScript, as a loosely typed language, the addition and concatenation operator is overloaded.

JavaScript is loosely typed, but that doesn't mean that it has no data types just because a value of a variable, object properties, functions or parameters don't need to have a particular type of value assigned to it.

Basically there are three primitive data types:

  • boolean
  • number
  • string

null and undefined are two special cases, everything else are just variations of the object type.

JavaScript type-converts values of types into a type suitable for the context of their use (type coercion).

In your example were trying to add two objects of type string, so a concatenation occur.

You can "cast" or type convert the variables to number in many ways to avoid this problem:

var a = "2";
var b = "4";
// a and b are strings!
var sum =  Number(a) + Number(b);          // Number constructor.
sum =  +a + +b;                            // Unary plus.
sum =  parseInt(a, 10) + parseInt(b, 10);  // parseInt.
sum =  parseFloat(a) + parseFloat(b);      // parseFloat.

This is I think a very common mistake, for example when reading user input from form elements, the value property of form controls is string, even if the character sequence that it contain represents a number (as in your example).

The "Bad Part" which I talk, is about the dual functionality of the + operator, overloaded to be used for both, numeric addition and string concatenation.

The operation that the + operator will do is determined completely by the context. Only if the both operands are numbers, the + operator perform addition, otherwise it will convert all of its operands to string and do concatenation.

like image 22
Christian C. Salvadó Avatar answered Nov 15 '22 20:11

Christian C. Salvadó


The single quotes cause the values to be treated as characters instead of numbers. '2' + '4' = '24' in the same way that 'snarf' + 'blam' = 'snarfblam'.

like image 36
snarf Avatar answered Nov 15 '22 20:11

snarf