Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Typesof

The typeof Operator

The typeof operator returns the data type of a variable in JavaScript.

Primitive Data Types

In JavaScript, a primitive value is a single value that lacks properties or methods.

There are 7 primitive data types in JavaScript:

  • string
  • number
  • boolean
  • bigint
  • symbol
  • null
  • undefined

The typeof operator returns the type of a variable or expression.

Examples

typeof “John”         // Returns string
typeof (“John”+“Doe”) // Returns string
typeof 3.14           // Returns number
typeof 33             // Returns number
typeof (33 + 66)      // Returns number
typeof true           // Returns boolean
typeof false          // Returns boolean
typeof 1234n          // Returns bigint
typeof Symbol()       // Returns symbol
typeof x              // Returns undefined
typeof null           // Returns object

Note: In JavaScript, null is considered a primitive value, but typeof returns “object.”

This is a well-known bug in JavaScript with historical roots.

Complex Data Types

A complex data type can hold multiple values and/or various data types together.

JavaScript has one complex data type:

  • object

All other complex types, such as arrays, functions, sets, and maps, are essentially different forms of objects.

The typeof operator returns only two types for complex data:

  • object
  • function

Example

typeof {name:‘John’}   // Returns object
typeof [1,2,3,4]       // Returns object
typeof new Map()       // Returns object
typeof new Set()       // Returns object

typeof function (){}   // Returns function

Note: The typeof operator returns “object” for all types of objects, including:

  • objects
  • arrays
  • sets
  • maps

You cannot use typeof to distinguish whether a JavaScript object is an array or a date.

How to Recognize an Array

How can you determine if a variable is an array?

ECMAScript 5 (2009) introduced a new method for this: Array.isArray().

Example

// Create an Array
const fruits = [“apples”“bananas”“oranges”];
Array.isArray(fruits);