DynamicPL/Javascript

Primitives vs. Objects

데먕 2019. 10. 24. 00:18

1. Overview

Let's distinguish differences between primitives and objects

2. Description

2.1 Difference

2.1.1 Primitives

Variables containing primitives actually hold that data inside of the variable itself.

2.1.2 Objectives

Variables associated objects do not actually contain the object but instead, they contain a reference to the place in memory where the object is stored. That means these variables don't have a real copy of the object.

3. Example

// Primitives
var a = 23;
var b = a;
a = 46;
console.log(a);
console.log(b);



// Objects
var obj1 = {
    name: 'John',
    age: 26
};
var obj2 = obj1;
obj1.age = 30;
console.log(obj1.age);
console.log(obj2.age);


var age = 27;
var obj = {
    name: 'Jonas',
    city: 'Lisbon'
};
// Functions
function change(a, b) {
    a = 30;
    b.city = 'San Francisco';
}

change(age, obj);

console.log(age);
console.log(obj.city);

Each primitive variable holds its own copy of the data. On the other hand, assigning to a new variable just create a reference that points to the original object. This is also applied to function.

4. References

https://codingheroes.io/