I started reading a book, Javascript for Kids. In it the author states that there are three data types:
However, according to W3Schools, there are four:
I wanted to know which one is correct.
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:
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"
ortypeof Date(2011,01,01)
"string"
2. Numbers
typeof 42
ortypeof NaN
, lol
"number"
3. Bool
typeof true
(valid values true
and false
)
"boolean"
4. Object
typeof {}
ortypeof []
ortypeof null
ortypeof /aaa/
ortypeof 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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With