Q: Passing JavaScript arrays to functions A general question on JavaScript. If I have a function which modifies an array, such as:
var some_array = [];

function a_function(input, array){

    //do stuff to array
    return array;

}

In most languages: 
var some_array = [];

some_array = a_function(input, some_array);

console.log(some_array);

works, however in js the below works as well: 
var some_array = [];

a_function(input, some_array);

console.log(some_array);

Is this correct and how is this working?

A: Arrays in JS are objects and are passed into functions by value, where that value is a reference to the array. In other words, an array passed as an argument to a function still points to the same memory as the outer array.
This means that changing the array contents within the function changes the array passed from outside the function.


function f(arr) {
  arr.push(1); 
  return arr;
}

var array = [];

// both function calls bellow add an element to the same array and then return a reference to that array. 

// adds an element to the array and returns it.
// It overrides the previous reference to the array with a 
// new reference to the same array.
array = f(array);
console.log(array); // [1]

// adds an element to the array and ignores the returned reference.
f(array);
console.log(array); // [1, 1]


