Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

language design - Why does !new Boolean(false) equals false in JavaScript?

From the jQuery documentation on JavaScript types comes this snippet of code describing the behavior of strings when converted to booleans (that topic is not related to this question, but it's just where I found the code):

!"" // true
!"hello" // false
!"true" // false
!new Boolean(false) // false

I get the first three examples, but I don't get the last example, because:

new Boolean(false) == false //true
!false // true

So I would assume:

!new Boolean(false) // true

But instead:

!new Boolean(false) // false, mind = blown

What is this I don't even...

Is it because:

new Boolean(false) === false // false

If so, what purpose does this serve?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

new Boolean(false) returns an object which is not null. Non-null objects are always truthy.

As a result, ! of any non-null object will always be false.


To prove it to yourself, you can run this in your javascript console

(typeof new Boolean(false))  //"object"

Also, you can use the strict equality operator to confirm that new Boolean(false) isn't really false:

new Boolean(false) === false  // false

Incidentally, calling the Boolean function as a function—without the new—actually does return a primitive

!Boolean(false) // true

(typeof Boolean(false))  //"boolean"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...