JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

What is pass by reference in JavaScript?

JavaScript uses pass by reference when an argument passed to the function is a reference variable or value.

In pass by reference, the changes made to the function parameters are reflected in the original arguments.

Note: Pass by reference is also known as call by reference. For pass by value, visit What is pass by value in JavaScript?

Let's understand how pass by reference works in JavaScript with the help of examples.

function update(employee){
  employee.name = 'Khushboo Natani';
}

let emp = {
  name: 'Mohit Natani'
}

update(emp);
console.log(emp); //{name:'Khushboo Natani'}

In this example, an object is passed to the function. The update() function changes the name of the employee. As you can see, an object is a reference variable, so JavaScript copies the reference of this object to the employee parameter. And inside the update() function, the name of the employee is changed to Khushboo Natani.

function add(arr){
  for(let i=0; i<arr.length; i++){
    arr[i] = arr[i] + 10;
  }
}

let evenArr = [2,4,6,8,10]
add(evenArr);

console.log(evenArr);//[12,14,16,18,20]

In another example, an array is passed to the function. The add() function adds 10 to every element of the array. As you know, an array is also a reference variable, so JavaScript simply copies the reference of the array to the arr parameter. The changes that are made to the arr parameter are reflected in the original array evenArr.

Recommended Posts