Introduction

Often, it’s necessary to check if a variable is of what kind to determine what operations to perform next.

The typeof operator

In JavaScript, everything that is not a primitive is an object. Primitives are, string, number, boolean, null or undefined

The typeof operator takes a single operand and returns string of the type of the operand given to the operator:

// The number primitve
const count = 0
console.log(typeof count) // number

// The boolean primitive
const switchStatus = false
console.log(typeof switchStatus) // boolean

// The null primitive
const nil = null
console.log(typeof nil)

// The undefined primitive
const notDefined = undefined
console.log(typeof notDefined) // undefined

// For non-primitives:
const states = ['GROUND', 'AIR', 'WATER']
console.log(typeof states) // object

Using typeof on Object literals and any non-primitive will always return “object”


Found this article helpful? You may follow me on Twitter where I tweet about interesting topics on software development.