1

I've been recently learning some javascript in action and get a little bit struck with not quite surely a performance problem which I think is connected to arrays. I wrote a short test function just to test if arrays are passed by reference. And they are. My only quiestion is:

How exactly is it passed?

There are no pointers in javascript, right?

Here are the test functions:

function arr_test(arr) {
    for (var i = 0; i < arr.length; i++) {
        arr[i] = 50;
    }
}

function num_test(num) {
    num = 50;
}

var array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
arr_test(array);
console.log(array);

var num = 10;
num_test(num);
console.log(num);

The output is as expected:

Array [ 50, 50, 50, 50, 50, 50, 50, 50, 50, 50 ]
10
Sorbet
  • 110
  • 1
  • 8

2 Answers2

1

Javascript passes values per references (except for primitive values such as string or numbers). There are pointers in JS (in fact almost everything but primitives are references), but they are hidden and automatically managed (like Java or Python for example).

The array is not copied. The one you get inside the function arr_test is the same as the one outside the function. As a result, if you change its value, it will be reflected outside the function.

However, in your num_test function, you are not updating the value of the number you are getting as parameter. What you are doing is assigning the num variable inside the function to another number somewhere else in the memory. The num variable outside the function is not changed. This is actually unrelated to the fact that num is passed as reference or variable. If instead of updating the arr[i] in arr_test you just did arr = [50, 50] (i.e. assigning another object to the given parameter instead of updating the one you have been provided), the array's value outside the function would not have been updated either.

Quentin Roy
  • 7,677
  • 2
  • 32
  • 50
  • Strings can be either object or primitive. Javascript will convert primitive into object when needed so that you can use the object's method with primitive strings. See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). – Quentin Roy May 20 '16 at 05:37
  • So every non-primitive variable is passed by reference. Great, that cleared some things out for me. Thanks – Sorbet May 20 '16 at 07:09
0

Pretty much everything is javaScript is an object .

Objects are passed by reference .

so when you pass an array (object) into a function and modify it , it persists .

Ahmed Eid
  • 4,414
  • 3
  • 28
  • 34