-13

In JavaScript, what is the difference between doing:

if (a !b)
{
// something here
}

and

if (a != b)
{
// something here
}

I know that '!' is 'logical not' and '!=' is 'not equal to', but I am not sure on the difference between the two. I have seen both examples used on SoloLearn projects though.

Neither of the above give any errors or warnings in my web browser (chrome). I'm not sure how to use chrome's debug console yet.

I don't mean "difference between !== and !===" btw.

2 Answers2

4

In JavaScript !foo is a boolean toggle so if foo = true; then !foo is checking to see if foo equals the opposite value in this case false,

your function:

if (a !b)
{
// something here
}

doesn't do anything, and should actually just be:

if (!b)
{
// something here
}

which tests to see if bis in the opposite state.

When you use != you are comparing two values to see if one doesn't equal to the other. so your function:

if {a != b)
{
// something here
}

checks to see if a doesn't equal b.

Cheers.

Mehrad
  • 1,202
  • 14
  • 20
1

A plain ! is a logical operator and indicates opposite. For example a common practice for toggling a boolean operator when you don't always know the current state would be the following:

// Toggle Foo, regardless of current value, assuming its of a boolean type.
var foo = !foo;

!= is an inequality operator and is used to test for "not equal" operator, it simply checks whether something is equal to whatever you are comparing it to.

Here is a great question about this in a more broad context.

joshrathke
  • 6,536
  • 5
  • 19
  • 36