Primitive Value Vs Objects

The primitive values are booleans, numbers, string, null and undefined. All other values are objects.
The major difference is their comparison and each object has the unique identity.

var obj1 = {};
var obj2 = {};

obj1 === obj2
false
obj1 == obj1
true

All the primitive values which has same value are considered as same value.

var val1 = '123';
var val2 = '123';

val1 === val2
true

Characteristics of Primitive values:

These are compared by the given content i.e;

5 === 5
true

'hello' ==  'hello'
true

These are always immutable.

Properties cannot be added, changed or removed.

var str = 'hello';
str.length = 2;
console.log(ex.length);
5
If we try to change the value of the length, it doesn't get effected.

str.abc = 3;
console.log(str.abc);
undefined

Here, we are trying to create a property of 'abc', but there will not be any effect. Reading an unknown property always returns undefined.

Objects :

All non-primitive values are referred as objects. The common ways of objects are:

1. Plain Objects :
{
    "firstName" : "Josh",
     "lastName" : "John"
}

2. Arrays :
Arrays are been created as Array Literals.

[ "one", "two", "three"]

3. Regular Literals :
These are created by regular expression literals.

Comparing the reference :

Identities are compared, each and every value has it own identity.

{} == {}  // two different empty objects
false

var obj1= {};
var obj2 = obj1;
obj1 == obj2;
true

Mutable by default :

We can add, remove, change or update properties.

var obj1 = {};
obj1.num = 11;
console.log(obj1.num);
11

undefined and null

These two are known as "nonvalues".

undefined values means "no value". The values which are not initialized are undefined.
var num = {};
num
undefined

Missing Parameters are also undefined.

function num(x) { return x; }
num();
undefined

If the property doesn't exist, then the result is undefined.

var num = {};
num.abc;
undefined

null means "no value".

No comments:

Post a Comment

Overview of AngularJS

AngularJS is an open source web application framework. It is now maintained by Google . The most of the code can be eliminated by using th...