33 Javascript Concepts — #5. Typeof & Instanceof

First of all, this story is based on Stephen Curtis -33 Fundamentals Every Javascript Developer Should Know and you can read it here.
I thought it is great concepts to know although it is not a requirement. So i decided to learn and explain these concepts one by one.

#5. Typeof & Instancof

Syntax

The typeofoperator is followed by its operand

typeof operand
typeof(operand)

Primitive types

console.log(typeof ‘medium’);  --> string
console.log(typeof true); --> boolean
console.log(typeof 7); --> number
console.log(typeof NaN); --> number
console.log(typeof Infinity); --> number
console.log(typeof undefined); --> undefined
console.log(typeof null); --> object??

In primitive types, everything is working correctly except typeof null which is considered as bug. A fix was proposed for ECMAScript, but was rejected. It would have resulted in typeof null === ‘null’
typeof is really useful when you want to check type of primitives except null

Object types (everything except primitive types)

function add(a, b) {
return a + b;
}
const arr = [1, 2, 3];const obj = {
name: ‘obj’,
};
console.log(typeof add); --> function
console.log(typeof arr); --> object
console.log(typeof obj); --> ojbect

typeof add and typeof obj respectively result in function and object. These results are pretty obvious and not a problem. typeof arr also results in object. This is not a bug since arrays are a special type of objects. However, in most common case, this is not what we want. What if we want to check if operand is object or array? In that case, we can use instanceof

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.

Syntax

object instanceof constructor

Array vs Object

const arr = [1, 2, 3];const obj = {
name: ‘obj’,
};
console.log(arr instanceof Array); --> true
console.log(obj instanceof Object); --> true
const arr = [1, 2, 3] is equal to
const arr = new Array(1, 2, 3)
const obj = { name : ‘obj’ } is equal to
const obj = new Object({ name: ‘obj’})

Since arr and obj are respectively instance of Array and Object you can distinguish them by using instanceof

primitives

console.log(‘medium’ instanceof String); --> false
console.log(1 instanceof Number); --> false
console.log(true instanceof Boolean); --> false

But in primitives, instanceof doesn’t work. All of them result in false

Conclusion

reference: MDN, Video

Junior React Front-end Developer, LinkedIn: https://www.linkedin.com/in/dh-kim-733227200/