/

JavaScript: Passing Values by Reference or by Value

JavaScript: Passing Values by Reference or by Value

In JavaScript, the way values are passed depends on whether they are primitive types or objects.

Primitive types, which include numbers, strings, booleans, null, undefined, and symbols, are passed by value. When a primitive value is passed to a function, a copy of that value is made, and any modifications made to the copy will not affect the original value.

For example:

1
2
3
4
5
6
7
8
const increment = num => {
num = num + 1;
}

const num = 2;
increment(num);

console.log(num); // Output: 2

On the other hand, objects, including arrays and functions, are passed by reference. This means that when an object is passed to a function, a reference to that object is actually passed. Any changes made to the object within the function will directly affect the original object.

For example:

1
2
3
4
5
6
7
8
9
10
11
const increment = obj => {
obj.value = obj.value + 1;
}

const num = {
value: 2
}

increment(num);

console.log(num.value); // Output: 3

It’s important to note that even though arrays and functions are technically objects in JavaScript, they are still passed by reference.

In summary, primitive types are passed by value, while objects (including arrays and functions) are passed by reference.

tags: [“JavaScript”, “objects”, “primitive types”, “pass by value”, “pass by reference”]