Created
August 4, 2018 05:59
-
-
Save au5ton/fd2c2fb8497821b1a14e5184c513bfe0 to your computer and use it in GitHub Desktop.
javascript pass by value versus pass by reference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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