JavaScript Data Types and Type Detection Methods
Primitive Types
JavaScript has seven primitive data types:
- Number
- String
- Boolean
- BigInt – introduced in ES2020, allows representation of integers with arbitrary precision, avoiding overflow errors with large numbers. Create BigInt values by appending
nto an integer (e.g.,647326483767797n) or using theBigInt()function (e.g.,BigInt("647326483767797")). - Symbol
- Null
- Undefined
Reference Types (Complex)
Object – includes plain objects, arrays, regular expressions, funcsions, etc. All non-primitive values are objects.
Methods for Determining Data Types
1. typeof operator
Returns a string indicating the type of the operand. Works for primitives (including function) but has known quirks:
typeof null; // "object" (incorrect, legacy behavior)
typeof Symbol(); // "symbol"
typeof String; // "function"
typeof String(); // "string"
typeof new String(""); // "object"
2. instanceof operattor
Checks whether an object is an instance of a constructor by traversing the prototype chain. Does not work with null or undefined because they are not objects.
[] instanceof Array; // true
null instanceof Object; // false (null is not an object)
"hello" instanceof String; // false (primitive string)
Important:
instanceofrequires the right operand to be a constructor (object). It cannot distinguish primitive types that are not objects.
3. constructor property
Every object has a constructor property that references the function that created its instance. Can be used for type checking but fails for null and undefined since they have no constructor.
(123).constructor === Number; // true
"text".constructor === String; // true
true.constructor === Boolean; // true
({}).constructor === Object; // true
4. Object.prototype.toString.call()
Invokes the internal [[Class]] property of any value, returning a string in the format [object Xxx]. This is one of the most reliable ways to determine built-in types. Works for null and undefined as well.
Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call("foo"); // "[object String]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(/x/); // "[object RegExp]"
Note: This method cannot differentiate custom object types created by user-defined constructors (it will return
[object Object]).