In JavaScript, all function arguments are always passed by value. It means that JavaScript copies the values of the passing variables into arguments inside of the function.
Any changes that you make to the arguments inside the function does not affect the passing variables outside of the function.
So, the changes made to the arguments are not reflected outside of the function.
let a = 10;
let b = a;
a = 20;
//a and b are two INDEPENDENT Variables
console.log(`a is: ${a}`); //a is: 20
console.log(`b is: ${b}`); //b is: 10
Understanding JavaScript Pass By Value
let numb = 10;
function increase(number){
number++;
}
increase(numb);
increase(numb);
increase(numb);
console.log(`number is: ${numb}`); //10
let numb = 10;
let increase = numb => {
console.log(`inside increase function argument numb is ${numb}`);
numb++;
console.log(`inside increase function after increment is ${numb}`);
}
increase(numb);
increase(numb);
console.log(`number is: ${numb}`); //10
let square = x => x = x * x;
let y = 10;
let result = square(y);
//template literals use `` and ${}
console.log(`The value of variable y is: ${y} `); // 10 -- no change
console.log(`The result is: ${result} `); // 100
Primitive types (also known as Value types)
- Number
- String
- Boolean
- Symbol -- new in ES6
- undefined
- null
So, when we're copying simple primitive types, we call that passing by value because we are literally taking that whole value and saving it in another variable.
Reference types
Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the data.
- Objects
- Arrays
- Functions
When we're doing it with more complex types, JavaScript isn't copying over the whole object, it's just copying a reference to it, so it's called passing by reference. So, if you had a complex object with thousands of properties in it or an array with millions of elements, then JavaScript isn't making copies of it in memory!
//Objects are copied by their referenc!
let a = { value: 10 };
let b = a;
a.value = 20;
console.log(`a.value is: ${a.value}`);
console.log(`b.value is: ${b.value}`);
//Both a and b are pointing to the same memory address