How many data types are there in JS, and what are they?

后端 未结 5 2074
难免孤独
难免孤独 2021-01-02 16:48

I started reading a book, Javascript for Kids. In it the author states that there are three data types:

  • numbers
  • strings
  • booleans
5条回答
  •  一个人的身影
    2021-01-02 17:07

    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...

提交回复
热议问题