The current edition of the ECMAScript spec defines 8 value types:
- Undefined
- Null
- Boolean
- String
- Symbol
- Number
- BigInt
- Object
https://262.ecma-international.org/11.0/#sec-ecmascript-language-types
The typeof operator is a big source of confusion in JavaScript, because what it returns is not always the actual type of the value. The conversion table for typeof (https://262.ecma-international.org/11.0/#sec-typeof-operator) is like this
| Type of val | Result |
|---|---|
| Undefined | undefined |
| Null | object !!! |
| Boolean | boolean |
| Number | number |
| String | string |
| Symbol | symbol |
| BigInt | bigint |
| Object (does not implement [[Call]]) | object |
| Object (implements [[Call]]) | function !!! |
Note the two exceptions marked with !!!
To confuse us further, the language also provides wrapper functions for these 4 primitive types
- Boolean
- Number
- String
- BigInt
These functions
when called with
new, return their argument converted to a corresponding wrapper object (Boolean,Numberetc)when called without
new, return their argument converted to a corresponding primitive value (Boolean, Number etc)
These functions are also called implicitly (in the new or "constructor" mode) when a primitive is used in the "object" context (e.g. "foo".length)
Videos
How do I check the data type of a variable in JavaScript?
Can JavaScript variables change their data type?
What is the difference between null and undefined in JavaScript?
You can test it using typeof operator:
The typeof operator gives you the names of data types when placed before any single operand.
Hence, try using typeof with any operand variable: it will give one of the following datatype names:
- String
- Number
- Boolean
- Object
- Undefined
Hence, these are the five data Types in Javascript.
var val1 = "New World"; //returns String
var val2 = 5; //returns Number
var val3 = true; //returns Boolean
var val4 = [1,2,3]; //returns Object
var val5 = null; //returns Object (Value is null, but type is still an object)
var val6; //returns Undefined
Things aren't actually as straightforward as they described in answers above... they usually aren't in javascriptland ;)
typeof is the 'official' function that one uses to get the type in javascript, however in certain cases it might yield some unexpected results ...
1. Strings
typeof "String" or
typeof Date(2011,01,01)
"string"
2. Numbers
typeof 42 or
typeof NaN, lol
"number"
3. Bool
typeof true (valid values true and false)
"boolean"
4. Object
typeof {} or
typeof [] or
typeof null or
typeof /aaa/ or
typeof Error()
"object"
5. Function
typeof function(){}
"function"
6. Undefined
var var1; typeof var1
"undefined"
Alternative is to use ({}).toString() which will get you somewhat more accurate answer most of the time...