« Back to Index

JavaScript pass by value/reference example

View original Gist on GitHub

pass.js

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
 */