0

I made a little bit of code:

function changeArrElem( arr ) {
    arr = [ 23, 63, 85 ];
}

let arr = [];

console.log( arr.join() );
console.log( "" );

changeArrElem( arr );

console.log( arr.join() );

I expected to see initialized array in the function but no. I see nothing. Output is empty. How to pass array by reference to initialize it inside a function?

JavaRunner
  • 2,455
  • 5
  • 38
  • 52
  • Well your array is empty from the start, since you never call the function that fills it. – Liora Haydont Jan 19 '18 at 22:34
  • @LioraHaydont, it's empty from the start sure. But then I call changeArrElem function and pass arr (I think) by reference but it's not. And finally after change that array inside changeArrElem (by reference) I have empty array again. – JavaRunner Jan 19 '18 at 22:37
  • 2
    The result is expected. Your function mutates a local variable, not a pointer to an external variable. To set its content, you'd need to mutate the array object itself, not the variable. `arr.push( 23, 63, 85 )` –  Jan 19 '18 at 22:39
  • @rockstar, well, then how to clear array by reference inside that function? – JavaRunner Jan 19 '18 at 22:40
  • 2
    @JavaRunner: `arr.length = 0;` will do it. –  Jan 19 '18 at 22:40
  • 1
    @rockstar, omg I didn't know it. I did: arr = []; - and it didn't help me. Your solution helped me. Thanks. – JavaRunner Jan 19 '18 at 22:42
  • 1
    @JavaRunner If you still want to know why, then take a look at [**this**](https://stackoverflow.com/questions/46259273/why-do-some-operations-not-alter-an-array-that-was-passed-to-a-function). – ibrahim mahrir Jan 19 '18 at 22:45

0 Answers0