Should I use !==
or ==!
? Both work, but what is the standard?
I enter "else" for both cases:
var x;
if (x !== undefined)
{
alert("if..");
}
else
{
alert('else..') // <--- here
}
var y;
if (y ==! undefined)
{
alert("if..");
}
else
{
alert('else..') // <--- here
}
Should I use !==
or ==!
? Both work, but what is the standard?
I enter "else" for both cases:
var x;
if (x !== undefined)
{
alert("if..");
}
else
{
alert('else..') // <--- here
}
var y;
if (y ==! undefined)
{
alert("if..");
}
else
{
alert('else..') // <--- here
}
Share
Improve this question
edited Oct 4, 2018 at 6:35
radbyx
asked Mar 7, 2014 at 9:47
radbyxradbyx
9,67022 gold badges90 silver badges133 bronze badges
2
-
1
1 !== 2
is true, but1 ==! 2
is false.==!
is wrong-spaced==
and!
– Alma Do Commented Mar 7, 2014 at 9:53 - Related: The negation operator in JS. – Sebastian Simon Commented Mar 17, 2022 at 11:09
2 Answers
Reset to default 6==!
is not a parison operator in Javascript. When you write foo ==! bar
, you are actually writing foo == !bar
, using the unary !
negation operator and the binary ==
parison operator. This probably does not do what you want it to:
> 'b' ==! 'a'
false
> 'b' !== 'a'
true
This happens to "work" in the particular situation you describe because !undefined
evaluates to true
, and y == true
for undefined y
is false
, thus putting you on the else
branch.
if (x !== undefined)
checks if x is not undefined, while
if (y ==! undefined)
negates undefiend
(which returns !undefined == true
) and then checks it for equality with y