Javascript Object Oriented Design - Javascript Primitive Types

Identifying Primitive Types

To identify primitive types, use the codetypeofcode operator.

codetypeofcode operator works on any variable and returns a string indicating the type of data.

The following shows the output when using typeof on different primitive values.

console.log(typeof "Javascript");     
console.log(typeof 10);               
console.log(typeof 1.1);              
console.log(typeof true);             
console.log(typeof undefined);        

The code above generates the following result.

typeof returns number when the value is an integer or floating-point values.

The following code shows that the uninitialized variable has type of undefined.

var a;
console.log(typeof a);  

The code above generates the following result.


null literal is an ill case.

typeof null returns object.

console.log(typeof null);

The code above generates the following result.


The best way to determine if a value is null is to compare it against null directly, like this

var string1 = red; 

console.log(string1 === null);       

string1 = null; 

console.log(string1 === null);    


The code above generates the following result.

The code above uses the triple equals operator === instead of the double equals operator ==.

The triple equals does the comparison without coercing the variable to another type.

Coercing the variable to another type means to convert the variable from one type to another.

To understand coercing, consider the following:

console.log("1" == 1);              // true 
console.log("1" === 1);             // false 

console.log(undefined == null);     // true 
console.log(undefined === null);    // false 

The code above generates the following result.

When using the double equals ==, the string "1" and the number 1 are considered equal because the double equals converts the string into a number before the comparison.

The triple equals === operator doesn't consider these values equal because they are two different types. Even though they have the same numeric value after converting.