1

Why is it that with null, the automatic type conversion is different with different binary operators?

console.log(null * 8) // => 0 * 8 => 0
console.log(null == 0) // => false

Therefore with the second statement, null doesn't get type coerced to a 0.

4
  • 2
    The language is defined that way. What is the problem you're trying to solve? Commented Dec 6, 2016 at 4:50
  • Not a specific problem I'm trying to solve, simply curious as to why the language works this way. Commented Dec 6, 2016 at 4:51
  • 1
    stackoverflow.com/questions/13407544/… Commented Dec 6, 2016 at 4:53
  • typeof null === 'object' Commented Dec 6, 2016 at 5:07

2 Answers 2

1

That's because, when you want to multiply, both operands must be numbers. Therefore, JS uses the ToNumber abstract operation, and ToNumber(null) is 0.

When you compare, the values don't need to be numbers. It makes sense to compare non-numerical values. So null is not coerced to a number.

Sign up to request clarification or add additional context in comments.

Comments

0

null is coerced to +0 for numeric operations. However, == is not a numeric operator and no type coercion is done thus giving null == 0 as false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.