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

SungJunEun·2021년 11월 26일
0

33 Key JS Concepts

목록 보기
5/14
post-thumbnail
post-custom-banner

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'

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

  1. Not walks up the prototype chain.

  2. 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.

profile
블록체인 개발자(진)
post-custom-banner

0개의 댓글