primitives vs objects

Primitives are immutable and passed by value.

Objects are mutable and stored by reference.

primitives

Primitives can not be changed after being set.

A variable can be reset to a new primitive but it doesn’t change the primitive that was created.

JavaScript

let number1 = 42;
let number2 = number1;
number2 = number2 / 2;

console.log('number 1: ' + number1); // 42
console.log('number 2: ' + number2); // 21

The primitives are

objects

Objects are mutable and stored by reference.

JavaScript

let object1 = {};
let object2 = object1;

object2.test = 'test';

console.log(object1); // {test: 'test'}
console.log(object2); // {test: 'test'}

object1 has the test property we gave to object2 because the variable object2 is pointing to object1.

A new object isn’t created when assigning object1 to object2 they both reference the same object in memory.

functions, arrays and objects are stored by reference.

JavaScript

let object1 = {};
let object2 = object1;

object2.test = 'test';

console.log(object1); // {test: 'test'}
console.log(object2); // {test: 'test'} 

let array1 = [];
let array2 = array1;

array2.push(1);

console.log(array1); // [1]
console.log(array2); // [1]


let functionOne = () => {}
let functionTwo = functionOne;

functionTwo.test = 'test';

console.log(functionOne.test); // test
console.log(functionTwo.test); // test

passing by reference vs passing by value

Passing by value is when a new instance is made.

Passing by reference is when a new instance isn’t made.

javascript
7 Git commands that every developer should know

Explanation of Git and 7 important Git commands.

javascript
first class functions in JavaScript

First class functions are functions that are treated like any other variable.