Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JavaScript handle the plus and minus operators between strings and numbers differently?

I don't understand why JavaScript works this way.

console.log("1" + 1); console.log("1" - 1); 

The first line prints 11, and the second prints 0. Why does JavaScript handle the first as a String and the second as a number?

like image 682
Nirgn Avatar asked Jun 24 '14 10:06

Nirgn


People also ask

What happens when you subtract strings in Javascript?

The unary minus will convert its argument ( "1" ) to a number ( 1 ) and take its inverse ( -1 ). The binary minus will convert its arguments ( "1" and -1 ) to numbers ( 1 and -1 ) and compute their difference ( 2 ).

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!

Why do we use numbers in Javascript?

Number is a primitive wrapper object used to represent and manipulate numbers like 37 or -9.25 . The Number constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the Number() function.

Can you subtract strings in JS?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.


1 Answers

String concatenation is done with + so Javascript will convert the first numeric 1 to a string and concatenate "1" and "1" making "11".

You cannot perform subtraction on strings, so Javascript converts the second "1" to a number and subtracts 1 from 1, resulting in zero.

like image 185
Bernhard Hofmann Avatar answered Oct 12 '22 01:10

Bernhard Hofmann