Some conversion behaviors in Javascript
"+" operator with String and a numbers:
In JavaScript, the
+
operator has different behaviors based on the context in which it's used. When you use the+
operator with a string and a number, JavaScript performs string concatenation.If we add String and a number together the JavaScript treats the
+
operator as a concatenation operator because one of the operands is a string. As a result, it concatenates the two values together as strings rather than performing addition.However, if we add the two numbers and then add it with string as shown in example 3 below then it first adds the two numbers then it concatenates the result with the last string value
console.log("2"+2); //Output:22 console.log("2"+2+2); //Output:222 console.log(2+2+"2"); //Output:42
"+" operator with boolean values
In JS when you use the unary plus
+
operator in front of a value, it attempts to convert that value into a number that's why when we use the + operator with boolean true we get the output as 1 as it converts it to a number and when we use + operator with boolean false we get the output as 0,console.log(true); //prints true console.log(+true); //converts to number and prints 1 console.log(false); //prints false console.log(+false); // converts to number and prints 0
"+" operator with empty String
In JavaScript, when you use the plus + operator with an empty string "", it attempts to convert the string into a number. and the result will be 0
console.log(+""); // converts to number and prints 0
+operator with undefined
In JavaScript, when you use the plus + operator with an undefined, it attempts to convert it into a number. and the resulting output will be NaN
console.log(+undefined); // converts to number and prints as NaN
"+" Operator with null
when we try converting null to a number, it evaluates to 0.
console.log(+null); // converts to number and prints 0
Comparison confusions:
If we compare numbers with string representation of numbers then below are the results
console.log(2 > "1"); // Outputs true (Number > String - String coerced to Number) console.log(2 < "12"); // Outputs false (Number < String - String coerced to Number) console.log(2 == "2"); // Outputs true (Loose Equality - String coerced to Number) console.log(2 == "02"); // Outputs true (Loose Equality - String coerced to Number)
"-" operator with string:
If the string has any numeric value then the minus operator tries to convert the string to a number and then displays the -ve number however if the string doesn't have any numeric value and we use the minus operator then the result will be NaN
console.log(-"2"); // Outputs -2 (Unary Minus converts String to Number) console.log(-"hello"); // Outputs NaN (Unary Minus cannot convert non-numeric string to Number)