Javascript Object Oriented Design - Javascript Primitive








Javascript primitive types stores data in memory as it is.

There are five primitive types in JavaScript:

TypeValue
Booleantrue or false
NumberInteger or floating-point numeric value
Stringtext delimited by either single or double quotes
NullA primitive type that has only one value, null.
UndefinedA primitive type that has only one value, undefined.

The last two, null and undefined, are special to Javascript.

Null and undefined has their own type of category.

undefined is the value assigned to a variable that is not initialized.





Literals

All primitive types have literal representations of their values.

The following are String literal:


// strings 
var name = "Javascript"; 
var s = "a"; 

name and s are two variables.

Number literal,


// numbers 
var count = 2; 
var cost = 12.251; 

Boolean literal


// boolean 
var found = true; 
var isValid = false;

Null Literal


// null 
var object = null; 

Undefined literal


// undefined 
var flag = undefined; 
var ref;    // assigned undefined automatically 

ref is assigned to value undefined since the variable ref is not assigned to any value.

When assigning a primitive value to a variable, the value is copied into that variable.

When assigning one variable equal to another, each variable gets its own copy of the data.

For example:


var string1 = "pink"; 
var string2 = string1; 

In the code above the 'pink' value is copied to string2 during the assignment.

The following code shows that changes to one variable are not reflected on the other.

For example:


var string1 = "red"; 
var string2 = string1; 
/*from   w  w  w. j  a v  a 2s  .c o  m*/
console.log(string1);    // "red" 
console.log(string2);    // "red" 

string1 = "blue"; 
console.log(string1);    // "blue" 
console.log(string2);    // "red" 

The code above generates the following result.

In this code, string1 is changed and string2 retains its original value.