« Back to Index

JS “pass by”

View original Gist on GitHub

JS pass by examples.js

function passPrimitive(arg) {
    arg = "new"
}

function passArray(arg) {
    arg.push("new")
}

function passObject(arg) {
    arg.x = "y"
}

function functionPropertyAttributes(arg) {
    arg = ["completely", "new", "array"]
}

var primitive = 123
passPrimitive(primitive) // primitive is still = 123 (primitives are passed by value)

var array = ["x", "y", "z"]
passArray(array) // array is now = ["x", "y", "z", "new"] as we passed a reference

var object = { "key": "value" }
passObject(object) // => object is now = { "key": "value", "x": "y" } as we passed a reference

var another_array = ["a", "b", "c"]
functionPropertyAttributes(another_array) 
// => another_array is still = ["a", "b", "c"] as we didn't modify the referenced Array passed to the function
// In this example we assigned a new Array to a local variable "arg" rather than modifying the referenced object

/*
Primitives are passed by value
Objects/Arrays (which are just objects) are passed by reference
*/