0

I just release something strange(at least to me) that happened in JavaScript(don't know maybe in other languages as well). I have this example:

var a = "1";
var b = 1;

console.log(a + b); // this one returns 11 as it suppose
console.log(b + a); // this one returns also 11 as it suppose
console.log(a + b + b); // this one returns 111? why not 12 ?
console.log(b + b + a); // but this return 21 as it suppose

Can someone explain to me why this happened?

1
  • The operations are processed from left to right. As soon as a string is encountered, it does concatenation. Otherwise it does the addition. Since b + b is encountered first, it's evaluated as addition, then concatenated with the a. You can look at the behavior here: es5.github.io/#x11.6.1 Commented Oct 3, 2014 at 18:34

2 Answers 2

2

Let's break down your code:

var a = "1",    // string
    b = 1;      // number

console.log(a + b);
// a is a string and b is a number
// read from left to right
// string first, so when + goes to concatenate the two variables, you get
// a + b.toString() == "1" + "1" == "11"

console.log(b + a);
// same thing as above because of the .toString() method
// except the + operator sees number + string (versus string + number)
// however, this still casts the number to a string, since that's how
// strings and numbers are concatenated

console.log(a + b + b)
// same as above
// read from left to right
// string is encountered first, so everything after it is cast to a string
// "1" + b.toString() + b.toString() == "1" + "2" + "2" == "122"
// if you want it to be 12, you need to do
// console.log(a + (b + b))

console.log(b + b + a)
// the first + operator sees two integers, so they get added together first
// now it's console.log(2 + a)
// so (2).toString() + a == "2" + "1" == "21", if you follow the logic
// from the second example
Sign up to request clarification or add additional context in comments.

Comments

1

a is a string, so when you do math operations on a string it simply concatenates. Lets go thru yours:

console.log(a + b + b); // a + b = 11 - which is now a string + b = 111;
console.log(b + b + a); // b + b = 2 + a string 1 = 21

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.