Mastering JavaScript Type Detection: typeof, instanceof, constructor & $.type
This article explores JavaScript's various techniques for determining variable types—including typeof, instanceof, constructor, Object.prototype.toString.call, and jQuery's $.type—by explaining their behavior, limitations, and practical examples with common data types.
Introduction
JavaScript defines five primitive data types—Undefined, Null, Boolean, Number, and String—and one complex type, Object. Objects include specific structures such as Array, Function, and Date. The article sets up several test variables representing these common types to demonstrate detection methods.
01. Using typeof to Detect Types
The
typeofoperator is the most frequently used way to check a variable's type. It correctly identifies Number, String, Boolean, Function, and Undefined, but treats arrays, JSON objects, dates, regular expressions, and errors as
object. It also cannot distinguish between
nulland
object.
02. Using instanceof to Detect Types
The
instanceofoperator, introduced in ECMAScript, determines whether an object is an instance of a specific constructor. Unlike
typeof, it can differentiate between built‑in objects such as Array and custom classes, but it still fails to detect primitive types like Number, String, and Boolean.
Additionally,
instanceofworks only with objects created in the current execution context; objects from different frames or windows have distinct constructor references, leading to false negatives.
03. Using constructor to Detect Types
Every object inherits a
constructorproperty that points to its creating function. By comparing
obj.constructorwith built‑in constructors (e.g.,
Number,
String), one can identify most types except
nulland
undefined. However, the
constructorproperty can be overwritten, which may produce inaccurate results.
04. Using Object.prototype.toString.call
This method returns a string like
[object Array]. The first part always indicates
Object, while the second part reveals the actual type. By extracting the second token, developers can reliably detect any JavaScript type, including
nulland
undefined.
05. jQuery’s $.type Implementation
jQuery provides
$.type, which internally uses
Object.prototype.toString.callto obtain the type string and then maps it to a lowercase type name (e.g.,
boolean,
array). For objects and functions, it falls back to
typeof. The article shows the relevant jQuery source code.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.