Skip to content

Instantly share code, notes, and snippets.

@au5ton
Created August 4, 2018 05:59
Show Gist options
  • Save au5ton/fd2c2fb8497821b1a14e5184c513bfe0 to your computer and use it in GitHub Desktop.
Save au5ton/fd2c2fb8497821b1a14e5184c513bfe0 to your computer and use it in GitHub Desktop.
javascript pass by value versus pass by reference
// Cannot replace with new references
let str = 'hello world'
function f(x) {x = x.substring(0,x.length-2)} // Removes last character
f(str)
// str => 'hello world'
function f(x) {x = 'new thing'}
f(str)
//str => 'hello world'
// Can modify object by original reference
ray = [1,2,3]
function g(x) {x.splice(1,1)} // Remove second value
g(ray)
// ray => [ 1, 3 ]
ray = [1,2,3]
function h(x) {for(let i in x){x[i] = x[i]+1;}} // Increment every value
h(ray)
// ray => [ 2, 3, 4 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment