Pass by value
Any change that you make to the arguments inside the function DOES NOT affect the passing variables outside of the function.
In other words, the changes made to the arguments are not reflected outside of the function.
Passing Primitives
function square(x) {
x = x * x;
return x;
}
var y = 10;
var result = square(y);
// what would these print out?
console.log(y);
console.log(result);
Resource: https://www.javascripttutorial.net/javascript-pass-by-value/
Passing Objects
When you pass an object to a function, you are passing the reference of that object, not the actual object.
Therefore, the function can modify the properties of the object via its reference.
BUT the function CANNOT change the reference variable to reference another object.
const number = 100
const string = "Jay"
let obj1 = {
value: "a"
}
let obj2 = {
value: "b"
}
let obj3 = obj2;
function change(number, string, obj1, obj2) {
number = number * 10;
string = "Pete";
obj1 = obj2;
obj2.value = "c";
}
change(number, string, obj1, obj2);
//Guess the outputs here before you run the code:
console.log(number);
console.log(string);
console.log(obj1.value);
Last updated