Merlin
Merlin

Reputation: 4917

What is the "===!" operator doing?

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..

Upvotes: 5

Views: 121

Answers (3)

epascarello
epascarello

Reputation: 207501

Whitespace means nothing so it is

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

which is

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

MDN Operator Precedence

Upvotes: 11

tckmn
tckmn

Reputation: 59273

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

Upvotes: 2

scrblnrd3
scrblnrd3

Reputation: 7416

! 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))))))))))))

Upvotes: 5

Related Questions