The typeof
operator returns the data type of a variable in JavaScript.
In JavaScript, a primitive value is a single value that lacks properties or methods.
There are 7 primitive data types in JavaScript:
The typeof
operator returns the type of a variable or expression.
typeof “John” // Returns string typeof (“John”+“Doe”) // Returns string typeof 3.14 // Returns number typeof 33 // Returns number typeof (33 + 66) // Returns number typeof true // Returns boolean typeof false // Returns boolean typeof 1234n // Returns bigint typeof Symbol() // Returns symbol typeof x // Returns undefined |
typeof null // Returns object |
Note: In JavaScript, This is a well-known bug in JavaScript with historical roots. |
A complex data type can hold multiple values and/or various data types together.
JavaScript has one complex data type:
All other complex types, such as arrays, functions, sets, and maps, are essentially different forms of objects.
The typeof
operator returns only two types for complex data:
typeof {name:‘John’} // Returns object typeof [1,2,3,4] // Returns object typeof new Map() // Returns object typeof new Set() // Returns object typeof function (){} // Returns function |
Note: The
You cannot use |
How can you determine if a variable is an array?
ECMAScript 5 (2009) introduced a new method for this: Array.isArray()
.
// Create an Array const fruits = [“apples”, “bananas”, “oranges”]; Array.isArray(fruits); |