JavaScript Basic
What are the data types in JavaScript? How do you identify a variable's data type?
What are the data types in JavaScript?
JavaScript data types are divided into two main categories:
Primitive Types
There are 7 primitive types:
string: Text values, e.g.'hello'number: Numeric values, e.g.42,3.14bigint: Large integers, e.g.9007199254740991nboolean:true/falseundefined: A variable that has been declared but not assigned a valuenull: Represents "no value" or "empty"symbol: Unique and immutable values (introduced in ES6)
Object Types
object: Includes plain objects, arrays, functions, etc.
How do you identify a variable's data type?
1. typeof Operator
The most common approach, but has some quirks:
typeof 'hello' // 'string'
typeof 42 // 'number'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof Symbol() // 'symbol'
typeof 42n // 'bigint'
typeof {} // 'object'
typeof [] // 'object' (arrays are also 'object'!)
typeof null // 'object' (a well-known historical bug)
typeof function(){} // 'function'
2. instanceof Operator
Checks whether an object is an instance of a particular constructor:
[] instanceof Array // true
{} instanceof Object // true
/regex/ instanceof RegExp // true
3. Object.prototype.toString.call()
The most accurate method — distinguishes null, arrays, functions, etc.:
Object.prototype.toString.call('hello') // '[object String]'
Object.prototype.toString.call(42) // '[object Number]'
Object.prototype.toString.call(null) // '[object Null]'
Object.prototype.toString.call([]) // '[object Array]'
Object.prototype.toString.call({}) // '[object Object]'
Object.prototype.toString.call(function(){}) // '[object Function]'
4. Array.isArray()
The recommended way to check specifically for arrays:
Array.isArray([]) // true
Array.isArray({}) // false
Summary
| Method | Best For | Caveats |
|---|---|---|
typeof |
Primitive types | Returns 'object' for null and arrays |
instanceof |
Checking object instances | Doesn't work for primitives |
Object.prototype.toString.call() |
Precise type checking for all types | More verbose |
Array.isArray() |
Checking for arrays | Recommended for array detection |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
