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?
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 ).
If you add a number and a string, the result will be a string!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With