Maizere Pathak
Maizere Pathak

Reputation: 299

javascript string and number variables

What does the following evaluate to?

"1"+2+4

What about this:

5 + 4 + "3"

In the first case since "1" is a string, everything is a string, so the result is "124". In the second case, its 93.what is happening here? Why does addition happen in one instance, while string concatenation occurs in the other?

var x = "1" + 2 + 4;
var z = 5 + 4 + "3";
console.log(x); // "124"
console.log(z); // 93 

Can anyone explain this?

Upvotes: 3

Views: 404

Answers (5)

john marker
john marker

Reputation: 41

In both case apply the type conversion and left to right precedence. in first one,

var x = "1" + 2 + 4; // 124

compiler take 1 as string and after that it will concatenating with 2 now 12 is the string so it will concatenate with 4 and result will produce "124" as string.

var z = 5 + 4 + "3"; // 93

in Second one, first 5 and 4 is numeric so make addition and result will be 9. and this will concatenate with string 3 soo output will be 93 as string.

Upvotes: 0

Kim D.
Kim D.

Reputation: 804

In the first case you create a string first (1) and then javascript concatenates the following number as strings (124).

In the second one you create a number first then javascript adds the second number to this first number (5 + 4 = 9) and then you add a string so it does the concatenation of 9 and 3

Upvotes: 0

Arpit
Arpit

Reputation: 12797

expression evaluates from left to right.

"1"+2+3
 ^--^
"12" //string  +3
  ^_____________^
 "123"  //string

in 2nd case

 1+2+"3"
 ^_^
  3+"3"
  ^___^
  "33" // string

Upvotes: 5

Hristo
Hristo

Reputation: 46517

var x = "1" + 2 + 4; // 124

This is taking the string "1" and concatenating to it "2" and "4" as strings.

var z = 5 + 4 + "3"; // 93

This is taking the numbers 4 and 5 and adding them together to get the number 9, and then concatenating the string "3" to that to produce another string.

The key thing to take away here is that the end result of what you're doing here is string concatenation. The order of evaluating the numbers is different but the end result is a string.

Upvotes: 0

Odinn
Odinn

Reputation: 808

Think about the operation order (rtl or ltr) each time it performs a binary operation it converts it accordingly so 5+4 will be int and (5+4) + "3" will be a string because "3" is a string

Same method applies to different examples

Upvotes: 1

Related Questions