Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does adding String with Integer work in JavaScript? [duplicate]

The following code gives weird results:

console.log("" + 1 + 10 + 2 - 5 + "8");

I've tried inputting various different values to work it out but I cannot understand what's going on under the hood.

like image 498
Arno Lorentz Avatar asked Nov 28 '16 16:11

Arno Lorentz


People also ask

What happens when you add a number and a string in JavaScript?

If you add a number and a string, the result will be a string!

What happens if you add a string to an integer using the operator in JavaScript?

In JavaScript, the + operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.

What happens when you add integer to string?

It happens because adding int and String gives you a new String. That means if you have int x = 5 , just define x + "" and you'll get your new String.

Can we concatenate string and integer in JavaScript?

In javascript, we can also concatenate strings with variables. We can do more than concatenate strings in Javascript: we can concatenate integers and booleans to strings.


2 Answers

"" + 1          === "1" "1" + 10        === "110" "110" + 2       === "1102" "1102" - 5      === 1097 1097 + "8"      === "10978" 

In JavaScript, the + operator is used for both numeric addition and string concatenation. When you "add" a number to a string the interpreter converts your number to a string and concatenates both together.

When you use the - operator, however, the string is converted back into a number so that numeric subtraction may occur.

When you then "add" a string "8", string concatenation occurs again. The number 1097 is converted into the string "1097", and then joined with "8".

like image 66
Phrogz Avatar answered Oct 09 '22 10:10

Phrogz


string + number = concatenated string

number + number = the sum of both numbers

string - number = the difference between (coerced string) and the number

explanation:

If one or both operands is string, then the plus is considered as string concatenation operator rather than adding numbers.

the minus operator always try to convert both operands to numbers.

so:

"" + 1 + 10 + 2 = (string) "1102"     "1102" - 5      = (number)  1097 1097 + "8"      = (string) "10798" 
like image 31
amd Avatar answered Oct 09 '22 12:10

amd