Question

I have just started playing the Azure Mobile Services stuff. It's super cool however there are a few weird things I have noticed while trying to change the server side database scripts. One specific thing is that while writing a simple statement like:

if (results.length == 0)

it warned me saying that I should use === instead of == while comparing with zero.

Anyone know why that is?

Was it helpful?

Solution

In loosely-typed languages, it's often useful to use === (strict equality operator) rather than == (equality operator), because otherwise the types of objects will be coerced during the equality check.

For example, "0" == 0, and "" == 0, and [] == 0.

However, none of those === 0.

So if results happened to be an object with an empty property length, like so:

var results = {
  length: ""
}

results.length == 0 would still evaluate to true.

OTHER TIPS

Because

[] == 0 

is true, but

[] === 0

Isn't.

Read about JavaScript comparison operators (and strict equality in particular).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top