JStypes

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
2
3
4
var s = "abcdef";
var ss = 'dsfasdgrg';
console.log(typeof s);
console.log(typeof ss);

Number

1
2
3
4
var n = 1204352;
var nn = 3.12354235;
console.log(typeof n);
console.log(typeof nn);

Boolean

1
2
3
4
var one = true ;
var zero = false ;
console.log(typeof one);
console.log(typeof zero);

Object type

Just like Python, so many things are objects

1
2
3
4
5
6
var array = [];
var dic = {} ;
var obj = { name : "V" , age : 30 };
console.log(typeof array);
console.log(typeof dic);
console.log(typeof obj);

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
2
3
4
5
int variable ;
/*
the value of variable can be any number ranging [-(2**31),2**31-1]
you can never know it
*/
1
2
var variable ; // uninitialized variable holds garbage value
console.log(typeof variable); // undefined

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
2
3
4
5
6
7
8
9
10
typedef struct node {
int data;
struct node * next ;
} Node ;


Node* find(Node* head){
// ...
if (notFound){ return NULL ;}
}
1
2
3
4
5
6
function find(Node head){
//...
if (notFound) { return null ;}
}

console.log(typeof null); // Object !!!!

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
2
3
4
5
6
7
float v = 3 / 0 ;
// warning: division by zero is undefined

float a = sqrt(-9) ;
// nan
// C also has this in some implementation !!!
// It even has inf
1
2
3
4
5
6
7
8
9
10
11
12
13
var a = 0 / 0 ;
var s = "ok" * 10 ;
var c = Math.sqrt(-9) ;


(NaN != NaN) == true ;
isNaN(NaN) == true ;


typeof NaN ; // number
// The result is still a number,
// but it just can't be represented correctly in computer
// So it still a number !

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
2
3
4
5
6
7
"hello" == 3
// "hello" -> NaN
// NaN != 3 -> false
"" == false
// "" -> 0
// false -> 0
// 0 == 0 -> true

Conclusion

If you want to strict type comparison, use === instead!