shreyansh shreyansh - 6 months ago 9
Javascript Question

How does type conversion happens in JavaScript?

(1) console.log(8*null)


// output to 0 ( null changes to 0)

(2) console.log("5"-1)


//output to 4 ("5" changes to 5)

(3) console.log("5"+1)


//output to "51" (1 changes to "1")

As if you see the above lines of code , some times type conversion happens on left hand side and some times it happens on right hand side of the binary operator.

So my question is how does JavaScript decides which operand type needs to be changed, does it happens internally (without in the knowledge of user) or is there any precedence of data type is there??

Answer
  1. Because * is a multiplicative operator, it calls the specification's ToNumber abstract operation on both of its operands (first the left one, then the right one). The result of ToNumber(null) is 0 (see the link for a table), so 8 * 0 is 0.

  2. Because - is a subtraction operator, it also calls ToNumber on its operands. So you get 5 - 1 which is 4.

  3. The + operator has two meanings: Mathematical addition, and string concatenation. If either operand is a string, you get concatenation, not addition. More formally: It first converts its operands to primitives via the spec's abstract ToPrimitive operation, and then determines whether either operand's primitive value is a string, and does concatenation if so. In the case of +, it doesn't matter which operand (the left or right) is a string, it can be either and that makes it concatenation rather than addition.

So my question is how does JavaScript decides which operand type needs to be changed, does it happens internally (without in the knowledge of user) or is there any precedence of data type is there??

It's spelled out in very, very thorough detail in the specification, so if you have any doubts in a particular situation, that's where to look.

Comments