Last active
December 28, 2015 16:29
-
-
Save emartinez-usgs/7529291 to your computer and use it in GitHub Desktop.
Example used to explain pass-by-value vs. pass-by-reference and which is used 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
/** | |
* This function assigns a new value to the input parameter. | |
*/ | |
var func1 = function func1 (param1) { | |
param1 = [4, 5 ,6]; | |
}; | |
/** | |
* This function acts on the input parameter. | |
*/ | |
var func2 = function func2 (param2) { | |
param2.splice(0, 3, 4, 5, 6); | |
}; | |
/** | |
* This function acts on the input parameter, assigns it a new value, then | |
* acts on it again. | |
*/ | |
var func3 = function func3 (param3) { | |
param3.splice(0, 3, 4, 5, 6); | |
param3 = ['a', 'b', 'c']; | |
param3.splice(0, 3, 'x', 'y', 'z'); | |
}; |
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
// step 1 | |
var x = set(); // returns [1, 2, 3] | |
func1(x); | |
log(JSON.stringify(x, null, 2)); | |
// step 2 | |
x = set(); | |
func2(x); | |
log(JSON.stringify(x, null, 2)); | |
// step 3 | |
x = set(); | |
func3(x); | |
log(JSON.stringify(x, null, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment