Created
July 27, 2012 08:02
-
-
Save Integralist/3186740 to your computer and use it in GitHub Desktop.
JavaScript pass by value/reference example
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
var my_num = 123; | |
var my_str = 'abc'; | |
var my_obj = { name: 'mark' }; | |
var my_arr = ['a', 'b', 'c']; | |
var my_bool = true; | |
var new_num = my_num; | |
var new_str = my_str; | |
var new_obj = my_obj; | |
var new_arr = my_arr; | |
var new_bool = my_bool; | |
++new_num; // increase value by 1 | |
new_str += 'def'; // add def to the end of the String | |
new_obj.age = 100; // add new property to the Object | |
new_arr.push('d'); // add new item to the end of the Array | |
new_bool = false; // reverse boolean value | |
console.group('Original'); | |
console.log(my_num); | |
console.log(my_str); | |
console.log(my_obj); | |
console.log(my_arr); | |
console.log(my_bool); | |
console.groupEnd(); | |
console.group('New'); | |
console.log(new_num); | |
console.log(new_str); | |
console.log(new_obj); | |
console.log(new_arr); | |
console.log(new_bool); | |
console.groupEnd(); | |
/* | |
* JavaScript types are split into two groups: primitive types and reference types. | |
* Numbers, Booleans, Strings, Null and Undefined types are primitive. | |
* Objects, Arrays, and Functions are reference types. | |
* | |
* So you'll notice that JavaScript passes Objects/Arrays/Functions by reference | |
* and passes primitives such as Booleans/Strings/Numbers by value | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment