What is the difference between primitives and objects?
Variables holding primitives actually holds the value of the primitive inside the variable.
Variables associated to an object doesn't hold the object but holds a reference to where the object is stored. It points to the object.
// Primitives
var a = 23;
var b = a;
a = 46;
console.log(a); // 46
console.log(b); // 23
// Objects
var obj1 = {
name: 'John',
age: 26
};
// New object is not created but rather a new reference to the same object is created
var obj2 = obj1;
obj1.age = 30;
console.log(obj1); // 30
console.log(obj2); // 30
// Functions
var age = 27;
var obj = {
name: 'Jonas',
city: 'Lisbon'
};
function change(a,b){
a = 30;
b.city = 'San Francisco';
}
change(age,obj);
console.log(age); // 27
console.log(obj.city); // San Francisco
When a primitive is passed to a function as an argument, rather than the actual variable, a copy will be passed. This means that the variable passed will not be affected.
When an object is passed, it's actually the reference to the object that is being passed and that is why the change is made to the object.