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 a string of the type of the operand given to the operator:

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

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

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

// 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”

Checking if a value is of type Array/is an Array with Array.isArray

Array.isArray is a static method call on the built-in Array object

To check if a variable/value is an array we use the inbuilt Array.isArray method:

const states = ['GROUND', 'AIR', 'WATER']
console.log(Array.isArray(states)) // true
// sample use
if(Array.isArray(states)) {
  // Do something here
}

Array.isArray(some_value) returns a boolean, true if the supplied value is an array, and false if the value is of other type.


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