Nathan
Nathan

Reputation: 672

JavaScript Equality Operator

In javascript whats the difference between undefined == variable and variable == undefined are both of them same? and how different will it be if i do undefined === variable or typeof variable == 'undefined'?

Can someone help me out

Upvotes: 1

Views: 1510

Answers (3)

Andreas
Andreas

Reputation: 1622

Don't use undefined to test for an undefined variable, use the typeof operator instead!

undefined isn't a javascript keyword, it's just a variable name. If someone writes var undefined = true globally anywhere into the code, all your comparisons will act unexpected.

You should consider using something like JSLINT or JSHINT to avoid these type of errors in your javascript code.

Apart from that, I would always write the compared parameter first, as that's the way I read it. That is why If the variable foo is undefined than should be written as if (typeof foo === "undefined")

I don't remember the name for this pattern, but I'm quite sure there is one :)

Upvotes: 1

Shylux
Shylux

Reputation: 1293

undefined == variable and variable == undefined are the same.

but i recomment undefined == variable to prevent strange behalves if you miss a = (variable = undefined).

undefined === variable and typeof variable == 'undefined' should also be the same.

Upvotes: 0

Tadeck
Tadeck

Reputation: 137450

There is no difference in meaning when it comes to different order of parts you mentioned.

=== is strict comparison, == is not. For example undefined == false is true, but undefined === false is not. Checking the undefined type is similar to strict comparison in this case.

Upvotes: 1

Related Questions