Quiz

How do you check the data type of a variable?

Topics
JavaScript

TL;DR

Use typeof for primitive categories and functions. Its possible results include "undefined", "boolean", "number", "bigint", "string", "symbol", "function", and "object". Because typeof null is historically "object" and arrays are objects, check those with value === null and Array.isArray(value). For specific object kinds, prefer purpose-built checks and be careful with instanceof across realms.


How do you check the data type of a variable?

Using the typeof operator

The typeof operator is the most common way to check the data type of a variable in JavaScript. It returns a string indicating the type of the operand.

let str = 'Hello, world!';
console.log(typeof str); // "string"
let num = 42;
console.log(typeof num); // "number"
let bool = true;
console.log(typeof bool); // "boolean"
let obj = { name: 'Alice' };
console.log(typeof obj); // "object"
let func = function () {};
console.log(typeof func); // "function"
let undef;
console.log(typeof undef); // "undefined"
let sym = Symbol();
console.log(typeof sym); // "symbol"
let big = 42n;
console.log(typeof big); // "bigint"

Checking for null

The typeof operator returns "object" for null, which can be misleading. To specifically check for null, you should use a strict equality comparison.

let n = null;
console.log(n === null); // true

Checking for arrays

Arrays are a special type of object in JavaScript. To check if a variable is an array, you can use the Array.isArray method.

let arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true

Checking for NaN

NaN (Not-a-Number) is a special numeric value in JavaScript. To check if a value is NaN, you can use the Number.isNaN method.

let notANumber = NaN;
console.log(Number.isNaN(notANumber)); // true

Checking for null and undefined

To check if a variable is either null or undefined, you can use a combination of the == operator and the typeof operator.

let value = null;
console.log(value == null); // true
let value2;
console.log(typeof value2 === 'undefined'); // true

Further reading

Exercícios

Verifique seu entendimento
Beta
Verifique seu entendimento Exercício
Verifique seu entendimento Exercício

Which JavaScript type checks are reliable for the stated purpose? Select all that apply.