Quiz

How do you check the data type of a variable?

Topics
JavaScript
在GitHub上编辑

TL;DR

To check the data type of a variable in JavaScript, you can use the typeof operator. For example, typeof variableName will return a string indicating the type of the variable, such as "string", "number", "boolean", "object", "function", "undefined", or "symbol". For arrays and null, you can use Array.isArray(variableName) and variableName === null, respectively.


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"

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

在GitHub上编辑