The typeof
assertion is beneficial in JavaScript for data validation and kind checking, but it surely has some odd options to concentrate on.
There are two situations when typeof
returns "object"
in an sudden approach, and this makes sort checking somewhat uncommon.
What Is the Typeof Assertion in JavaScript?
Typeof
is an announcement that’s utilized in JavaScript to test the kind variable in your code. It will probably return considered one of JavaScript’s eight information sorts, and it’s particularly helpful for returning many of the primitive sorts in JavaScript, together with undefined
, string
and quantity
.
Each typeof
null
and typeof
an array return "object"
in a doubtlessly deceptive approach, as null
is a primitive sort (not an object), and arrays are a particular, built-in sort of object in JavaScript.
On this article, I study each doable results of typeof
in JavaScript.
Information Varieties
Whereas there are solely eight data types (seven primitives and objects) in JavaScript, typeof
will really return considered one of 9 choices:
undefined
object
(that meansnull
)boolean
quantity
bigint
string
image
operate
object
(that means any object, together with arrays)
These correspond to the JavaScript information sorts, with the exception that the typeof
null
can be "object"
because of a long-standing bug.
Subsequent, I clarify when to count on every response from typeof
intimately.
Undefined
An undefined
worth in JavaScript is fairly frequent. It means a variable title has been reserved, however no worth has been assigned to that reference but. It’s not outlined but, so we name it undefined.
The worth undefined
is a primitive sort in JavaScript, and undeclared variables are additionally thought-about to be undefined.
Referencing undeclared variables normally ends in a ReferenceError, besides when utilizing the typeof
key phrase.
The typeof
undefined
is the string "undefined"
— and undefined is a falsy worth that’s loosely equal to null
however to not different falsy values.
// The worth undefined is loosely equals to null however not different 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 key phrase returns "undefined" for the worth undefined:
console.log(typeof undefined) // undefined
// A declared variable that has not been assigned a worth 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 secure strategy to test if a variable has been declared:
console.log(typeof undeclaredVariable)
// Referencing an undeclared variable with out typeof will throw a ReferenceError:
strive undeclaredVariable catch(e) console.log(e) // ReferenceError: undeclaredVariable isn't outlined
If typeof
says a worth is "undefined"
, then it’s a secure wager to imagine that worth is definitely undefined
, that means it was not declared, declared however by no means assigned a worth or declared and assigned the worth of undefined
.
Null Object
For historic causes, the typeof
null
in JavaScript is "object"
. This can be a bug that’s anticipated to by no means be fastened in JavaScript.
That signifies that checking for null can’t be carried out utilizing typeof
.
Nevertheless, null checking is fairly simple utilizing the strict equality operator (===
) to test that the worth is certainly null
, as in maybeNull===null
.
Helpful Issues to Know About Null
- The worth
null
is falsy (evaluates to false in a conditional). - The values
null
andundefined
are solely loosely equal to one another. - Neither
null
norundefined
are equal to different falsy values.
Because of this checking for null utilizing the unfastened equality (==
) operator will seize each null and undefined values, which may be helpful:
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 one falsy object
console.log(!null && typeof null === "object") // true
isNull = (worth) => !worth && typeof worth === "object"
console.log(isNull(null)) // true
Typically, an undefined
worth means the identical factor as a null
worth — the absence of a worth — so, utilizing ==
is advisable to test for null.
However, checking for null may be carried out simply with the strict equality ===
operator.
Or one can test by realizing that for the reason that empty object is truthy (evaluates to Boolean true
in a conditional), null
is the one falsy object.
Boolean
Checking for Boolean values is simple. They’re going to be both true
or false
, and the typeof
a boolean returns "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 factors !! (the logical NOT) operator are equal to Boolean()
console.log(typeof !!(37)) === // boolean
console.log(typeof !!(0)) === // boolean
// Conditionals will coerce values to boolean in the identical approach:
37 ? console.log("truthy") : console.log("falsy") // truthy
0 ? console.log("truthy") : console.log("falsy") // falsy
Word that JavaScript will coerce any worth to true
or false
through the use of the Boolean() wrapper function, which places two exclamation factors (the logical NOT — !
) in entrance of the expression. Or it’ll put the assertion within a conditional, similar to an if assertion, question mark ?
operator, or loop.
The values that consider to false
are known as the falsy values, and every part else in JavaScript evaluates to true
and is a truthy worth.
The falsy values in JavaScript are false
, 0
, 0n
, null
, undefined
, NaN
and the empty string “”
. The whole lot else is truthy.
Quantity
Checking for a quantity in JavaScript works as anticipated, with typeof
returning "quantity"
:
console.log(typeof 37) // "quantity"
console.log(typeof 2.71828) // "quantity"
console.log(typeof Math.E) // "quantity"
console.log(typeof Infinity) // "quantity"
// The typeof NaN is "quantity" despite the fact that NaN means "Not-A-Quantity":
console.log(typeof NaN) // "quantity"
// Calling Quantity explicitly is one strategy to parse a quantity:
console.log(typeof Quantity(`1`)) // "quantity"
// The parseInt and parseFloat features are different methods to parse:
console.log(typeof parseInt(`100`)) // "quantity"
console.log(typeof parseFloat(`100.01`)) // "quantity"
// Parse failures result in NaN, and NaN poisons different math:
console.log(typeof (2 * parseInt(`invalid`))) // "quantity"
Word that which means checking for NaN
requires checking for self-equality as a result of NaN
is the one worth in JavaScript that doesn’t equal itself:
const mightBeNaN = NaN // NaN means "Not-a-Quantity"
// Something compares false when in comparison with NaN:
console.log(37 === NaN) // false
console.log(mightBeNaN === NaN) // false
// NaN is the one worth that doesn't equal itself:
console.log(mightBeNaN !== mightBeNaN) // true
// Creating an invalid Date ends in the worth NaN:
console.log(new Date(`invalid`) !== new Date(`invalid`)) // true
// For improved code readability, some builders choose Quantity.isNan():
console.log(Quantity.isNan(mightBeNaN)) // true
BigInt
Checking for the primitive sort BigInt
works as anticipated; typeof
for supported browsers will return "bigint"
:
console.log(typeof 37n) // bigint
“BigInt is a built-in object that gives a strategy to characterize entire numbers bigger than 253 – 1, which is the most important quantity JavaScript can reliably characterize with the Number primitive. BigInt can be utilized for arbitrarily giant integers,” in line with the MDN web documentation.
Formally, BigInt
was added to trendy JavaScript as a part of ES11 (ECMAScript 2020), and it is supported by Chrome, and thus by Node.js, Firefox and Edge.
String
As one may hope, checking for a string in JavaScript is fairly straight-forward. typeof
works precisely as anticipated, returning "string"
:
console.log(typeof '37') // string
console.log(typeof "37") // string
console.log(typeof `37`) // string
// Word that typeof at all times returns a string:
console.log(typeof (typeof 37)) // string
// The String() wrapper operate converts something right into a string:
console.log(String(37))
It positive is sweet when issues work like they need to when programming.
Image
The primitive information sort symbol is a singular identifier, helpful for creating keys on objects in JavaScript.
“An emblem worth could also be used as an identifier for object properties; that is the info sort’s solely objective,” in line with MDN web docs.
As one would count on, the typeof Image()
is certainly "image"
:
console.log(typeof Image()) // image
console.log(typeof Image(37)) // image
console.log(typeof Image.iterator) // image
const symbolUno = Image()
const symbolDos = Image(37)
const symbolTres = Image("37")
console.log(typeof symbolUno) // image
console.log(String(symbolTres)) // Image(37)
// Each image worth returned from Image() is exclusive:
console.log(Image() === Image()) // false
console.log(Image(37) === Image(37)) // false
console.log(Image("37") === Image("37")) // false
Perform
Features are simply checked for utilizing the typeof
key phrase, which works fully as anticipated by returning "operate"
:
console.log(typeof operate myFunction() ) // operate
console.log(typeof class myClass ) // operate
console.log(typeof (() => )) // operate
// This contains built-in features, for instance Quantity.isNaN():
console.log(typeof Quantity.isNaN) // "operate"
// However not properties, after all:
console.log(typeof "".size) // "quantity"
// And calling a operate will test the typeof the return worth:
console.log(typeof Quantity.isNaN()) // "boolean"
console.log(typeof Quantity.isNaN(37)) // "boolean"
Object (Which means Object or Array)
So long as the worth in query isn’t null, typeof
returning "object"
signifies that the JavaScript worth is a JavaScript object.
One sort of object that’s constructed into JavaScript is the array, and the typeof
of an array is "object"
: typeof [] === `object` // true
.
ECMAScript 5 launched an Array.isArray()
technique to check for an array, since typeof
won’t be able to inform arrays from different objects.
The JavaScript prototypes Date
and RegExp
are two different forms of built-in objects the place typeof
returns “object.” Thus, dates and common expressions want extra differentiation than simply utilizing the typeof
key phrase.
Right here’s methods to test the kind of objects and arrays:
const helloWorldObject = good day: "world"
console.log(typeof helloWorldObject) // 'object'
// use Array.isArray or Object.prototype.toString.name
// to distinguish common 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's one other helper operate, although it's a bit lengthy:
console.log(Object.prototype.toString.name(helloWorldObject)) // [object Object]
console.log(Object.prototype.toString.name(fibonacciArray)) // [object Array]
// Common expression have their very own native object, RegExp
const myRegExp = /search/
console.log(typeof myRegExp) // 'object'
console.log(myRegExp instanceof RegExp) // true
console.log(Object.prototype.toString.name(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 somewhat trickier
console.log(emptyDate instanceof Date)
console.log(invalidDate instanceof Date)
console.log(Object.prototype.toString.name(invalidDate)) // [object Date]
// Dependable date checking requires a NaN test by checking for NaN:
console.log(invalidDate instanceof Date && !Quantity.isNaN(invalidDate.valueOf())) // true
The verbose JavaScript assertion Object.prototype.toString.call()
can differentiate between generic objects, arrays and different objects as a result of it returns a string that specifies the thing sort in additional element than typeof
.
Equally, the helper technique Array.isArray()
or the key phrase instanceof
can be utilized to test for arrays or any sort of object, respectively.
Typeof and Object Wrappers Defined
The object wrappers for Boolean, quantity and string will break typeof
and end in "object"
as an alternative of "boolean"
, "quantity"
, or "string"
.
// "The next are complicated, harmful, and wasteful. Keep away from them." -MDN Docs
typeof new Boolean(false) === 'object'; // true
typeof new Quantity(37) === 'object'; // true
typeof new String(`Hiya World!`) === 'object'; // true
Why do these object wrappers exist in the event that they shouldn’t be known as explicitly?
Principally, calling a string property like "".size
ends in JavaScript making a wrapper object and decoding the code this fashion:
"".size === String("").size // true
Since that occurs robotically, there isn’t any must create an specific wrapper object, as it’ll solely break typeof
, as proven above.
Why You Shouldn’t Use Wrapper Objects
Equally, wrapper objects change the operate of the ==
and ===
equality operators in JavaScript.
And the habits solely really modifications when the new key phrase is used with the thing wrapper name, as is proven within the following instance:
const primitiveString = `Hiya world!` // primitive sort string
const wrappedString = new String(`Hiya 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(`Hiya world!`) // wrapper known as with out new
console.log(typeof almostWrappedString) // "string"
console.log(primitiveString === almostWrappedString) // true
Typically talking, the string, Boolean and quantity wrappers might be known as robotically and shouldn’t be known as by JavaScript builders.
Typeof and Host Objects in JavaScript
Host objects are implementation-dependent, that means they’re provided by the native run-time atmosphere.
Put one other approach, host objects are particular objects past the usual built-in objects or native objects JavaScript offers.
For instance, the window
object is provided by the browser-environment provides, whereas a node.js atmosphere provides different host objects.
Because of this the typeof
key phrase can be implementation-dependent, a minimum of within the case of host objects.
That being stated, trendy implementations are in all probability going to return “object” because the typeof
host objects. For instance:
typeof window // "object"
Are Static Varieties the Future in JavaScript?
Since JavaScript is a dynamically typed language however typeof
has its quirks, some builders choose automated or static sort checking utilizing a language like TypeScript or a static sort checker like Movement.
Utilizing TypeScript or Movement positively has some benefits and may forestall bugs, however at the price of studying and implementing one other software.
Whereas helpful, utilizing both TypeScript or Movement will add an entire new layer of complexity to your JavaScript programming.
For vanilla JavaScript, mastering typeof
is all you want with a purpose to test information sorts like a champion.
Benefits of Typeof in JavaScript
The key phrase typeof
is beneficial for sort checking in JavaScript, but it surely has some caveats related to historic bugs.
Kind checking with typeof
is particularly helpful for many of the primitive sorts in JavaScript, together with undefined
, string
and quantity
.
However, Array
, Date
and Common Expressions
are native objects that aren’t differentiated from one another by typeof
. All of them return "object"
— as does null
, unexpectedly in a widely known bug.
In brief, typeof
is an imperfect however highly effective software to test a worth’s sort.