of typeof
statement is helpful JavaScript for data validation and type checking, but there are some strange features to be aware of.
I have two instances. typeof
Return value "object"
In an unexpected way, this changes the type checking a bit.
What is the Typeof Statement in JavaScript?
Typeof
A statement used in JavaScript to check type variables in code. It can return one of JavaScript’s eight data types, and is especially useful for returning most of JavaScript’s primitive types. undefined
, string
and number
.
both typeof
null
and typeof
of arrangement return "object"
in a potentially misleading manner, null
is a primitive type (not an object), and an array is a special built-in type of object in JavaScript.
This article explores all possible outcomes. typeof
in JavaScript.
data type
There is only 8 data types (7 primitives and objects) In JavaScript, typeof
It actually returns one of the following nine options:
undefined
object
(meaningnull
)boolean
number
bigint
string
symbol
function
object
(meaning any object, including arrays)
These correspond to JavaScript data types. typeof
null
again "object"
Due to longstanding bugs.
It then describes when to expect each response from. typeof
In detail.
undefined
Ann undefined
JavaScript values are fairly common. This means that the variable name is reserved, but that reference has not yet been assigned a value. We call it undefined because it hasn’t been defined yet.
value undefined
is a primitive type in JavaScript and undeclared variables are also considered undefined.
Referencing an undeclared variable usually raises a ReferenceError. typeof
keyword.
of typeof
undefined
is a string "undefined"
– and undefined is a false value roughly equal to null
But not for other false values.
// The value undefined is loosely equals to null but not other falsy values:
console.log(undefined === undefined) // true
console.log(undefined === null) // false
console.log(undefined == null) // true
console.log(Boolean(undefined)) // false
console.log(undefined == false) // false
// The typeof keyword returns "undefined" for the value undefined:
console.log(typeof undefined) // undefined
// A declared variable that has not been assigned a value is undefined by default:
let undefinedVariable
console.log(undefinedVariable) // undefined
console.log(typeof undefinedVariable) // undefined
// The typeof an undeclared variable is undefined, making it a safe way to check if a variable has been declared:
console.log(typeof undeclaredVariable)
// Referencing an undeclared variable without typeof will throw a ReferenceError:
try { undeclaredVariable } catch(e) { console.log(e) } // ReferenceError: undeclaredVariable is not defined
If typeof
value is "undefined"
the value is actually undefined
means undeclared, declared but not assigned a value, or declared and not assigned a value undefined
.
null object
For historical reasons, typeof
null
in JavaScript "object"
This is a bug that is not expected to be fixed in JavaScript.
In other words, you can’t do it with a null check. typeof
.
However, the null check uses the strict equality operator (===
) value is actually null
,like maybeNull===null
.
Useful things to know about Null
- value
null
is false (evaluates to false in the condition). - its worth
null
andundefined
They are only roughly equal to each other. - do not have
null
orundefined
Equal to any other falsy value.
This means checking for null using a loose equality (==
) operator captures both null and undefined values. This is useful.
console.log(null) // null
console.log(typeof null) // "object"
console.log(null === null) // true
console.log(null === undefined) // false
console.log(null == undefined) // true
console.log(null == false) // false
console.log(Boolean(null)) // false
// Alternatively, null is the only falsy object
console.log(!null && typeof null === "object") // true
isNull = (value) => !value && typeof value === "object"
console.log(isNull(null)) // true
In many cases, undefined
value means the same as a null
value – absence of value – hence use ==
It is recommended to check for null.
Checking for null, on the other hand, is easy to do with strict equality. ===
operator.
Or you can check it by knowing empty object is true (evaluates to a boolean true
conditional), null
The only fake.
boolean value
Checking booleans is easy.they will be either true
again false
and the typeof
a boolean value Return value "boolean"
:
console.log(typeof true) // boolean
console.log(typeof false) // boolean
// The Boolean() wrapper will convert truthy and falsy values:
console.log(typeof Boolean(37)) // boolean
console.log(typeof Boolean(0)) // boolean
// Two exclamation points !! (the logical NOT) operator are equivalent to Boolean()
console.log(typeof !!(37)) === // boolean
console.log(typeof !!(0)) === // boolean
// Conditionals will coerce values to boolean in the same way:
37 ? console.log("truthy") : console.log("falsy") // truthy
0 ? console.log("truthy") : console.log("falsy") // falsy
JavaScript accepts arbitrary values as true
again false
using Boolean() wrapper functiontwo exclamation points ( logical negation — !
) before the expression. Or put the statement inside a conditional such as an if statement. question mark ?
operatoror a loop.
Evaluated value false
These are called falsy values, and all other values in JavaScript are evaluated as follows: true
which is the true value.
Falsy values in JavaScript are: false
, 0
, 0n
, null
, undefined
, NaN
and an empty string “”
Everything else is true.
number
Checking numbers in JavaScript works as expected. typeof
return "number"
:
console.log(typeof 37) // "number"
console.log(typeof 2.71828) // "number"
console.log(typeof Math.E) // "number"
console.log(typeof Infinity) // "number"
// The typeof NaN is "number" even though NaN means "Not-A-Number":
console.log(typeof NaN) // "number"
// Calling Number explicitly is one way to parse a number:
console.log(typeof Number(`1`)) // "number"
// The parseInt and parseFloat functions are other ways to parse:
console.log(typeof parseInt(`100`)) // "number"
console.log(typeof parseFloat(`100.01`)) // "number"
// Parse failures lead to NaN, and NaN poisons other math:
console.log(typeof (2 * parseInt(`invalid`))) // "number"
this is, NaN
Because you need to check for self-equality NaN
The only value in JavaScript that is not equal to itself.
const mightBeNaN = NaN // NaN means "Not-a-Number"
// Anything compares false when compared to NaN:
console.log(37 === NaN) // false
console.log(mightBeNaN === NaN) // false
// NaN is the only value that does not equal itself:
console.log(mightBeNaN !== mightBeNaN) // true
// Creating an invalid Date results in the value NaN:
console.log(new Date(`invalid`) !== new Date(`invalid`)) // true
// For improved code readability, some developers prefer Number.isNan():
console.log(Number.isNan(mightBeNaN)) // true
BigInt
Checking primitive types BigInt
works as expected. typeof
For supported browsers it will return "bigint"
:
console.log(typeof 37n) // bigint
“BigInt is a built-in object that provides a way to represent integers greater than 253 – 1. This is because JavaScript uses number Primeval. BigInt can be used for arbitrarily large integers. MDN web docs.
Officially, BigInt
Added to modern JavaScript as part of ES11 (ECMAScript 2020). Supported By Chrome, and thus by Node.js, Firefox, and Edge.
string
As you can imagine, checking strings in JavaScript is very easy. typeof
works as expected and returns "string"
:
console.log(typeof '37') // string
console.log(typeof "37") // string
console.log(typeof `37`) // string
// Note that typeof always returns a string:
console.log(typeof (typeof 37)) // string
// The String() wrapper function converts anything into a string:
console.log(String(37))
It sure is nice when things work as they should programming.
symbol
primitive data types symbol A unique identifier, useful for creating keys for objects in JavaScript.
“Symbol values can be used as identifiers for object properties. That’s the sole purpose of data types. MDN web docs.
As I expected, type Symbol()
surely "symbol"
:
console.log(typeof Symbol()) // symbol
console.log(typeof Symbol(37)) // symbol
console.log(typeof Symbol.iterator) // symbol
const symbolUno = Symbol()
const symbolDos = Symbol(37)
const symbolTres = Symbol("37")
console.log(typeof symbolUno) // symbol
console.log(String(symbolTres)) // Symbol(37)
// Every symbol value returned from Symbol() is unique:
console.log(Symbol() === Symbol()) // false
console.log(Symbol(37) === Symbol(37)) // false
console.log(Symbol("37") === Symbol("37")) // false
function
The function is typeof
A keyword that works perfectly as expected by returning "function"
:
console.log(typeof function myFunction() {}) // function
console.log(typeof class myClass {}) // function
console.log(typeof (() => {})) // function
// This includes built-in functions, for example Number.isNaN():
console.log(typeof Number.isNaN) // "function"
// But not properties, of course:
console.log(typeof "".length) // "number"
// And calling a function will check the typeof the return value:
console.log(typeof Number.isNaN()) // "boolean"
console.log(typeof Number.isNaN(37)) // "boolean"
object (meaning object or array)
Unless the value in question is null typeof
return "object"
means that the JavaScript value is a JavaScript object.
One type of object built into JavaScript is an array. typeof
array of "object"
: typeof [] === `object` // true
.
Introduced in ECMAScript 5 Array.isArray()
how to check arraysince typeof
Arrays cannot be distinguished from other objects.
JavaScript prototype Date
and RegExp
are two other types of built-in objects. typeof
Returns an “object”. So for dates and regular expressions, typeof
keyword.
Here’s how to check the type of objects and arrays:
const helloWorldObject = { hello: "world" }
console.log(typeof helloWorldObject) // 'object'
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
const fibonacciArray = [1, 1, 2, 3, 5, 8]
console.log(typeof fibonacciArray) // 'object'
console.log(Array.isArray(helloWorldObject)) // false
console.log(Array.isArray(fibonacciArray)) // true
// There is another helper function, though it is a bit long:
console.log(Object.prototype.toString.call(helloWorldObject)) // [object Object]
console.log(Object.prototype.toString.call(fibonacciArray)) // [object Array]
// Regular expression have their own native object, RegExp
const myRegExp = /search/
console.log(typeof myRegExp) // 'object'
console.log(myRegExp instanceof RegExp) // true
console.log(Object.prototype.toString.call(myRegExp)) // [object RegExp]
// The Date native object is built-in to JavaScript
const emptyDate = new Date()
const invalidDate = new Date("fail")
console.log(typeof emptyDate) // 'object'
console.log(typeof invalidDate) // 'object'
// Checking for a date is a little trickier
console.log(emptyDate instanceof Date)
console.log(invalidDate instanceof Date)
console.log(Object.prototype.toString.call(invalidDate)) // [object Date]
// Reliable date checking requires a NaN check by checking for NaN:
console.log(invalidDate instanceof Date && !Number.isNaN(invalidDate.valueOf())) // true
Detailed JavaScript statements Object.prototype.toString.call()
Returns a string that further specifies the object type, so you can distinguish between generic objects, arrays, and other objects. typeof
.
Similarly, the helper method Array.isArray()
or keyword instanceof
They can be used to check arrays or objects of any type, respectively.
Explanation of Typeof and Object wrapper
of object wrapper For booleans it breaks numbers and strings typeof
and as a result "object"
Excluding that "boolean"
, "number"
again "string"
.
// "The following are confusing, dangerous, and wasteful. Avoid them." -MDN Docs
typeof new Boolean(false) === 'object'; // true
typeof new Number(37) === 'object'; // true
typeof new String(`Hello World!`) === 'object'; // true
Why do these object wrappers exist if they don’t need to be called explicitly?
Basically you call a string property like "".length
JavaScript creates a wrapper object and interprets your code as follows:
"".length === String("").length // true
There is no need to create an explicit wrapper object as this is done automatically. typeof
as shown above.
Why not use a wrapper object
Similarly, the wrapper object is ==
and ===
JavaScript equality operator.
And what actually changes the behavior is new Keywords are used in object wrapper calls, as shown in the following example.
const primitiveString = `Hello world!` // primitive type string
const wrappedString = new String(`Hello world!`) // wrapper object
console.log(typeof primitiveString) // "string"
console.log(typeof wrappedString) // "object"
console.log(primitiveString == wrappedString) // true
console.log(primitiveString === wrappedString) // false
const almostWrappedString = String(`Hello world!`) // wrapper called without new
console.log(typeof almostWrappedString) // "string"
console.log(primitiveString === almostWrappedString) // true
Generally speaking, string, boolean, and number wrappers are called automatically and should not be called by JavaScript developers.
JavaScript Typeof and Host Objects
The host object is implementation dependent. That is, host objects are provided by the local runtime environment.
In other words, host objects are special objects beyond the standard built-in and native objects that JavaScript provides.
for example, window
object The node.js environment provides other host objects, but provided by the browser environment.
this is, typeof
Keywords are also implementation dependent, at least for host objects.
That said, modern implementations probably refer to “objects” as typeof
host object. for example:
typeof window // "object"
Are static types the future of JavaScript?
JavaScript is a dynamically typed language, typeof
Some developers prefer automatic or static type checking using languages like TypeScript or static type checkers like Flow.
Using TypeScript or Flow certainly has some advantages and can prevent bugs, but it comes at the cost of learning and implementing another tool.
While convenient, using either TypeScript or Flow adds a whole new layer of complexity to JavaScript programming.
For vanilla JavaScript, mastering typeof
That’s all you need to check for data types like champ.
Benefits of Typeof in JavaScript
keyword typeof
is useful for type checking in JavaScript, but has some caveats related to historical bugs.
type checking typeof
Especially useful for most primitive types in JavaScript. undefined
, string
and number
.
on the other hand, Array
, Date
and Regular Expressions
Native objects that are not distinguished from each other by typeof
they will all be back "object"
– that’s right null
unexpectedly in a well-known bug.
in short, typeof
An imperfect but powerful tool for checking value types.