# JavaScript: Pass by Value vs Pass by Reference

JavaScript handles **primitive** and **non-primitive** data types differently when passing them to functions. It uses **pass by value** for primitives and **pass by reference** for objects.

## **Pass by Value (Primitive Data Types)**

When you pass a **primitive value** (e.g., numbers, strings, booleans, `null`, `undefined`, `Symbol`, or `BigInt`) to a function, JavaScript creates a **copy** of the value. Any modifications inside the function do not affect the original variable

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739133075929/df89c58b-7667-46db-aeca-9519b0dc36f4.png align="center")

.

### **Example: Pass by Value**

```javascript
let number = 10;

function modify(number) {
    number = number * 2;
    console.log(`The value of inside number is : ${number}`);
}
modify(number);
console.log(`The value of number is : ${number}`);
```

```javascript
The value of inside num is : 20
The value of number is : 10
```

* In this code, we are pass number as parameter in function modify.
    
* `number` variable holds the value 10;
    
* Next we call function modify, passing it the argument number which contains value 10.
    
* Any change inside the modify(), does not change the value for outside number variable because we are passing copy of number .
    
* ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739133728670/4a9264e4-1517-4800-a0a0-3f08268609f8.png align="center")
    

## 2\. Pass by Reference (Objects & Arrays)

When you pass an **object** (including arrays and functions) to a function, JavaScript passes a **reference** to the memory location of that object. Any modifications affect the original object.

### **Example: Pass by Reference**

```javascript
function modify(obj) {
    obj.value = 50;  // Modifies the original object
}

let myObj = { value: 10 };
modify(myObj);
console.log(myObj.value);
```

Output

```javascript
50
```

* In this code, first create myObj variable that contain the reference of the object.
    
* Next , we then call modify(), pass myObj as argument.
    
* modify() modify the value that myObj variable point to and update the vaue.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739134464549/ed349d9a-0b10-4e90-8fe1-c3b8dbed8f3d.png align="center")

## **Pass by Reference with Arrays**

Since arrays are objects, they also behave in a **pass-by-reference** manner.

```javascript
function modifyArray(arr) {
    arr.push(4);  // Modifies the original array
}

let numbers = [1, 2, 3];
modifyArray(numbers);
console.log(numbers);
```

Output

```javascript
[ 1, 2, 3, 4 ]
```
