Created
December 13, 2012 22:54
-
-
Save nicholasbs/4280863 to your computer and use it in GitHub Desktop.
How are variables passed to functions in JavaScript?
This file contains 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
/* | |
* JavaScript variables are always passed by value. This works as you | |
* expect it to when you pass primitives to functions. | |
*/ | |
function add1(x) { | |
// We get passed a copy of x's value -- which is a number -- so we can't | |
// update the original variable's value | |
x++; | |
} | |
var x = 0; | |
add1(x); | |
console.log("x is", x); // "x is 0" | |
/* | |
* What happens when we pass an object? JavaScript still passes by value, but | |
* the value we're passing is a *reference* to the object. | |
*/ | |
function setName(obj) { | |
// We get passed a copy of obj's value -- which is a reference -- so we can | |
// still update its properties | |
obj.name = "Nick"; | |
} | |
var obj = {}; | |
setName(obj); | |
console.log("obj.name is", obj.name); // "obj.name is Nick" | |
/* | |
* Further exploration: What about boxed objects? | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment