JS Coding Questions Logo
JS Coding Questions
#442💼 Interview💻 Code

What is pass by value and pass by reference?

Advertisement

728x90

Pass-by-value creates a new space in memory and makes a copy of a value. Primitives such as string, number, boolean etc will actually create a new copy. Hence, updating one value doesn't impact the other value. i.e, The values are independent of each other.

javascript
1let a = 5;
2
3let b = a;
4
5b++;
6
7console.log(a, b); //5, 6

In the above code snippet, the value of a is assigned to b and the variable b has been incremented. Since there is a new space created for variable b, any update on this variable doesn't impact the variable a.

Pass by reference doesn't create a new space in memory but the new variable adopts a memory address of an initial variable. Non-primitives such as objects, arrays and functions gets the reference of the initiable variable. i.e, updating one value will impact the other variable.

javascript
1let user1 = {
2
3name: "John",
4
5age: 27,
6};
7
8let user2 = user1;
9
10user2.age = 30;
11
12console.log(user1.age, user2.age); // 30, 30

In the above code snippet, updating the age property of one object will impact the other property due to the same reference.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 13

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
442of476