This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Osarumense Idukpaye
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
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}
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Osarumense Idukpaye
Osarumense Idukpaye | Sciencx (2023-01-28T20:28:35+00:00) Javascript (JS) Pass by Reference and Pass by Value. Retrieved from https://www.scien.cx/2023/01/28/javascript-js-pass-by-reference-and-pass-by-value/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.