DEV Community

Osarumense Idukpaye
Osarumense Idukpaye

Posted on

Javascript (JS) Pass by Reference and Pass by Value

Terms

Passing: To assign a value to a variable or, pass it to function as a parameter.

Pass by Value

Anytime a variable containing another value which is not an object or an array is passed along to let's say a function as a parameter, the variable being passed becomes a copy of the value it holds. As a result, the variable passed to the function will have its value unchanged despite whatever the function does with it, for example, reassign’s it or updates it.

let x = 60 
console.log (x) // 60

function boo (y){
    y = 70 
    console.log (y) // 70
}

foo(x) 
console.log (x) // 60 : unchanged value of the x variable
Enter fullscreen mode Exit fullscreen mode

Pass by Reference

Anytime a variable containing another value which is an object or array is passed along to let say a function as a parameter, the variable is passed to the parameter as a ref to its object/array value. As a result, the variable passed to the function will have its value changed if for example it is updated with a new element of the key/value pair.

let x = {
    name:"john",
    age:22
} 
console.log (x) // {name:"john",age:22} 

function boo (y){
    y.statue = true
    console.log (y) // {name:"john",age:22, status:true} 
}

foo(x)
console.log (x) // {name:"john",age:22, status:true} 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)