Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null is type object, so it's truthy? What's going on behind the scenes?

I'm reading in my book, "Elegant JavaScript", that null == true evaluates as false. Using an interpreter, I have confirmed this to be TRUE. However, later in the chapter--in fact, on the same page--, it says that when null is given as the condition of an if, while, or for statement, it will be converted to a Boolean and return false.

Can anybody with a deeper insight tell me why this is? I know where to find browser source code, but I'm not sure how to target the programming that is responsible for this peculiar and unintuive behavior. Because I know very little C++, I would also appreciate any tips on finding info like this, independently.

Thank you.

like image 664
千里ちゃん Avatar asked Jan 19 '23 14:01

千里ちゃん


2 Answers

An important distinction to make is that the Type of null is Null.

(ignore typeof it returns "object" for null because of bad design and backwards compatibility)

11.9.3 The Abstract Equality Comparison Algorithm # Ⓣ The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

[... stripped]

  1. Return false.

The ES5 specification

Says that the comparison with null and a Boolean should return false because the Type of Null and Boolean are not the same, and none of the other steps in 11.9.3 apply so the default action of return false happens

The only case where the Type of x and y are different and either x or y is null but the == operation still returns true are

If x is null and y is undefined, return true.

If x is undefined and y is null, return true.

That means undefined == null returns true

Of special note:

There is an ES6:harmony proposal to fix typeof null

like image 169
Raynos Avatar answered Jan 21 '23 04:01

Raynos


Actually I think he refers to the fact that typeof null == 'object', which is unfortunately the case. But that's a peculiarity of the typeof operator, not of null itself. Null is falsy value, but typeof returns "object" for it, according to the spec: http://bclary.com/2004/11/07/#a-11.4.3

like image 25
deviousdodo Avatar answered Jan 21 '23 05:01

deviousdodo