when I pass a variable as a function parameter, is a new copy of the variable value or a memory reference javascript
When I pass a variable as a function parameter, is a new copy of the variable value or a memory reference in JavaScript?
When you pass a variable as a function parameter in JavaScript, it depends on the variable type whether it is passed as a copy of the value or a reference to the memory location.
Primitive Data Types:
Primitive data types (such as numbers, strings, and booleans) are passed as a copy of the value.
let num = 5;
function changeNum(num) {
num = 10;
}
changeNum(num);
console.log(num); // Output: 5
In the above example, the original value of num
is not changed because the changeNum
function creates a new copy of the num
variable inside its scope. Even though this copy has the same name, it has a different memory location than the original num
variable.
Reference Data Types:
Reference data types (such as objects and arrays) are passed as a reference to the memory location.
let arr = [1, 2, 3];
function addItem(array) {
array.push(4);
}
addItem(arr);
console.log(arr); // Output: [1, 2, 3, 4]
In the above example, the original arr
value is changed because the addItem
function receives a reference to the memory location of the arr
variable. This means that any changes made to the array inside the function will affect the original array as well.
Passing Objects by Value:
It is possible to pass an object as a copy of its value by creating a new object inside the function and copying the properties of the original object to the new object.
let obj = { name: "John", age: 30 };
function changeName(newObj) {
newObj.name = "Jane";
}
changeName(Object.assign({}, obj));
console.log(obj.name); // Output: John
In the above example, a new object is created using the Object.assign()
method and passed to the changeName
function. This method creates a shallow copy of the obj
object, and any changes made to the new object will not affect the original object.
Overall, it is important to understand whether a variable is passed by value or by reference when working with functions in JavaScript, as it can affect how changes made inside a function affect the original variable.