How do you check the data type of a variable?
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.
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.
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.
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.
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.