JavaScript: The deal with ===

Thursday, June 19th, 2008

Most people don’t seem to use the === operater in JavaScript. Some lists of JavaScript operators don’t even include it. It is not as useless as the community’s negligence would suggest. There are times when it can be used to write more precise code. So what does it do, anyway?

== asks: Are these the same value? (“500″ == 500) is true though one is a string and one is a number.
=== asks: Are these the same type and the same value? (500 === 500) is true, but the above is not.
Both operators ask: “Are these the same object?” in the case of object comparison.

Some of the implications are subtle.

Primatives and the objects that represent them are different types with the same value.
(5 == new Number(5)) is true.
(5 === new Number(5)) is false.

Undefined and null are different types but have the same value.
(null == undefined) is true.
(null === undefined) is false.

False has the same value as primatives that evaluate to false.
(false == 0) is true.
(false === 0) is false.

True does not have the same value as primatives that evaluate to true.
(true == “Greg”) is false.
(true === “Greg”) is false.

Being aware of the difference will let you better understand your code’s behavior, and allow you to pick the right operator for the job.

For example, use (arg === undefined) to check if an optional argument was provided. If you use (!arg) or (arg == undefined) some odd things might happen, like explicit null being treated as an omitted argument.

Know that saying “if (foo)” and “if (foo == true)” and “if (foo === true)” are all different. (Try setting foo to each of 5, true, and new Boolean(true))

Always use the strictest operator possible. Use looser operaters when you’re sure you want to allow the “fuzzier” behavior. === is very strict, so it is a good tool to have in the old toolbelt.

No Comments

Leave a comment

About | Other Stuff