最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Should I use !== or ==! when checking for not equal? - Stack Overflow

programmeradmin0浏览0评论

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, but 1 ==! 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
Add a ment  | 

2 Answers 2

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

发布评论

评论列表(0)

  1. 暂无评论