Types

representation of data

Primitive Types:

The variable that directly contains the value. Ex: var num = 5;

Non-Primitive Types (Reference Types):

The variable doesn't contains the direct value. Ex: var obj = { a: "Vijay" };

Pass By Value:

Ex: a=10; b=3;

Here a of 10 will be assigned to some memory and b of 3 will be assigned to some memory. They don't know about each other's existence.

var a = 10;
var b = a;
b += 1;
console.log(a); // 10
console.log(b); // 11

The value of a will not be changed when we changing the value of b because only the value of a will be copied to b but not it's reference. In coping the primitive value's they will copies only its value.

Pass By Reference:

var obj1 = { name: 'name', pwd: '123' };
var obj2 = obj1;
obj2.pwd = '12345';

console.log(obj1); // { name: 'name', pwd: '12345' }
console.log(obj2); // { name: 'name', pwd: '12345' }

In References type variables, it will not copies the value, it copies the reference address. So when one object is modified, it changes all it's reference objects.

To remove the reference we use deep copy and shallow copy methods.

Shallow copy:

In shallow copy method, we use Object.assign or spread operation methods to copy the objects.

Ex:
var obj1 = { name: 'name', pwd: '123' };
var obj2 = Object.assign({},  obj1); // Object.assign method
var obj3 = {...obj1}; // spread operation method
obj2.pwd = '12345';

console.log(obj1); // { name: 'name', pwd: '123' }
console.log(obj2); // { name: 'name', pwd: '12345' }

The drawback in shallow copy is that it will removes the reference of the direct properties of the object, if the obj1 has another object, it's reference will not be removed.

Ex:
var obj1 = { name: 'name', pwd: { value: '123' } };
var obj2 = Object.assign({},  obj1); // Object.assign method
var obj3 = {...obj1}; // spread operation method
obj2.name = 'updated_name';
obj2.pwd.value = '12345';

console.log(obj1); // { name: 'name', pwd: { value: '12345' } }
console.log(obj2); // { name: 'updated_name', pwd: { value: '12345' } }

Deep copy:

To overcome the drawback of shallow copy we use deep copy method. It will removes all the references of the object and all inner object references.

Ex:
var obj1 = { name: 'name', pwd: { value: '123' } };
var obj2 = JSON.parse(JSON.stringify(obj1));
obj2.name = 'updated_name';
obj2.pwd.value = '12345';

console.log(obj1); // { name: 'name', pwd: { value: '123' } }
console.log(obj2); // { name: 'updated_name', pwd: { value: '12345' } }

Last updated