Articles
- JavaScript Double Equals vs. Triple Equals — Brandon Morelli done
- Should I use === or == equality comparison operator in JavaScript? — Panu Pitkamaki done
- == vs === JavaScript: Double Equals and Coercion — AJ Meyghani done
- Why Use the Triple-Equals Operator in JavaScript? — Louis Lazaris done
- What is the difference between == and === in JavaScript? — Craig Buckler done
- Why javascript's typeof always return "object"? — Stack Overflow list of ambiguous examples
- Checking Types in Javascript — Toby Ho done
- How to better check data types in JavaScript — Webbjocke done
- Checking for the Absence of a Value in JavaScript — Tomer Aberbach done
Checking Data type is not easy in Javascript.
== vs ===
==
- Operates loose equality
- Does type coercion ### ===
- Operates strict equality
- Both type and value have to be same to return
true
typeof vs instanceof
typeof
typeof returns object
for all values except primitve type. (null
is one exception.)
typeof([1,2,3]); // 'object'
typeof({}); // 'object'
typeof(1); // 'number'
typeof(null); // 'object'
It is ueless to distinguish between different kinds of objects.
instanceof
It checks whether object is instance of certain type.
function Animal(){};
var a = new Animal();
console.log(a instanceof Animal); // true
console.log([1,2,3] instanceof Array); // true
We can use constructor
method to check the type.
console.log(a.constructor == Animal); // true
console.log([1,2,3].constructor = Array); // true
problems of instanceof
Not walks up the prototype chain.
Error with primitve values.
console.log(3 instanceof Number); // false
console.log(true instanceof Boolean); // false
For alternative, we can use constructor
method for number, string, boolean type values. This works because, Javascript autoboxes given primitive type values with object wrapper. Precisely, it makes primitive value to object type, so this is why it works.
console.log((3).constructor == Number); // true
console.log('abc'.constructor == String); // true
Spinoff
Absence of a value
Undefined vs null
undefined
represents the value that doesn't exists in compiler. Following situations returns undefined
. undefined
is not a literal , it is a property of global object.
unassgined variable
undeclared object property
default return value of function which doesn't returns
value using void operator
null
however, represents the intentional absence of vaule. There is a bug with null
using typeof method.
console.log(typeof null); // object
Performance
strict equality is no slower than loose equality because they both check the operand types.
strict equality is faster than loose equality when types of operands differ.
of course, loose equality produces unexpected results.
Top comments (0)