admin管理员组

文章数量:1410712

I'am playing with some JavaScript and found something strange.

This code alerts "false" but gives no syntax errors. Someone could explain why adding one or even many !!! after === is no resulting with any errors ?

var i = void 0;
var b = i ===! void 0  ? "true" : "false";
alert(b);//display false but no syntax errors..

I'am playing with some JavaScript and found something strange.

This code alerts "false" but gives no syntax errors. Someone could explain why adding one or even many !!! after === is no resulting with any errors ?

var i = void 0;
var b = i ===! void 0  ? "true" : "false";
alert(b);//display false but no syntax errors..
Share Improve this question edited Oct 3, 2016 at 21:33 Merlin asked Jan 7, 2014 at 19:09 MerlinMerlin 4,9272 gold badges34 silver badges53 bronze badges 2
  • 1 ! is negating the following statement, even if the following statement is an ! – RienNeVaPlu͢s Commented Jan 7, 2014 at 19:11
  • 1 And why should it? ! is just a negation, so multiple ! will just invert each other – Alma Do Commented Jan 7, 2014 at 19:11
Add a ment  | 

3 Answers 3

Reset to default 11

Whitespace means nothing so it is

var b = (i === (!void 0))  ? "true" : "false";

which is

var b = (i === true) ? "true" : "false";

MDN Operator Precedence

! is just a negation, and it is right-associative, unlike most other operators, so it will just negate whatever is in front of it

This is essentially equivalent to

var b = i ===(!void 0) ? "true" : "false";

So basically, you could have as many !s in front of something as you want, and it wouldn't make a difference, so !!!!!!!!!!!!!false, would evaluate to true, because it is the same thing as !(!(!(!(!(!(!(!(!(!(!(!(!false))))))))))))

See this table, which may help explain:

!0 // true
!!0 // false
!!!!!!0 // false, showing that !s are simply prefixes
! 0 // true, showing whitespace is irrelevant
0 === !0 // false
0 ===! 0 // false
0 ===!!! 0 // false

本文标签: javascriptWhat is the quotquot operator doingStack Overflow