JavaScript Type System
One may find that JS type system is quiet confusing, and it is.
But if you spot them from a C
perspective, thing might be a bit more understandable
Basic types
JS only have three basic types, JSON representable types
String
1 | var s = "abcdef"; |
Number
1 | var n = 1204352; |
Boolean
1 | var one = true ; |
Object type
Just like Python
, so many things are objects
1 | var array = []; |
Functions are also objects
javascript - Why does typeof function return function? - Stack Overflow
Undefined
Just “Garbage Value”, the container sits there but it holds garbage
1 | int variable ; |
1 | var variable ; // uninitialized variable holds garbage value |
Null (Object)
The NULL
pointer in C
JavaScript objects are all referred by pointer/reference, so when the obj doesn’t exist, a null
is returned
1 | typedef struct node { |
1 | function find(Node head){ |
NaN (Number)
NaN, not a number, represent an “error” in arithmetic
The result is still a number, but it just can’t be represented correctly in computer
1 | float v = 3 / 0 ; |
1 | var a = 0 / 0 ; |
Comparison
Rule 1:
when string
vs number
, always convert string
to number
Rule 2:
when boolean
vs number
, always convert to number
(That’s natural, true is 1, false is 0)
Rule 3:
undefined
and null
are equal, since they both represent “no value”
Examples
1 | "hello" == 3 |
Conclusion
If you want to strict type comparison, use ===
instead!