DEV Community

MOYED
MOYED

Posted on

5. ==, ===, typeof, instaceof

Articles


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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

We can use constructor method to check the type.

console.log(a.constructor == Animal); // true

console.log([1,2,3].constructor = Array); // true
Enter fullscreen mode Exit fullscreen mode

problems of instanceof

  1. Not walks up the prototype chain.

  2. Error with primitve values.

console.log(3 instanceof Number); // false
console.log(true instanceof Boolean); // false
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)