4

I have a function

function x10(a,b)

I define a as an array a = [1]. And the function x10 pushes b zeros to a

x10 = function(a,b) {
  output = a;
  for(i=0;i<b;i++)
    output.push(0);
    return output;
}

I do NOT want this function to modify the argument a. If I write

print(a)
y = x10(a,2)
print(a)

I want a to be the same. Instead I get a = [1] before and a = [1,0,0] after. How do I prevent a from changing while allowing y to take the desired value.

Liam
  • 27,717
  • 28
  • 128
  • 190
  • What is the problem with this? – VLAZ Dec 30 '19 at 09:55
  • Related [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Liam Dec 30 '19 at 10:55

3 Answers3

3

The array a is passed as a reference. That's why in your case a gets modified.

In ES6, you can use the spread operator to copy a new value.

Note: This will do a shallow copy

x10 = function(a,b) {
  output = [...a];
  for(i=0;i<b;i++)
    output.push(0);
  return output;
}

The important change is:

output = [...a];

This article may shed some more on light on what's happening.

C.OG
  • 6,236
  • 3
  • 20
  • 38
  • 2
    "In JS primitive values are passed by value, whilst objects and arrays are passed by reference" - I know what you mean, but that's a misleading thing to say. Function arguments in JavaScript are passed by value. When you pass an object, you actually pass the reference to the object by value. More info here: https://stackoverflow.com/a/430958/8338 – Alexey Lebedev Dec 30 '19 at 10:45
  • Very true, thanks for the link, I have modified my initial statement. – C.OG Dec 30 '19 at 10:48
-1

var a = [1];
var x10 = function(a,b) {
  output = a.slice(0);
  for(i=0;i<b;i++)
    output.push(0);
    return output;
}

console.log(x10(a, 3));
console.log(a);
Ahed Kabalan
  • 815
  • 6
  • 8
-2

Try this way.It will works

let a= [1];
x10=function(a,b)
{
  output =[].concat(a); //add this line instead of output = a
  for(i=0;i<b;i++)
    output.push(0);
    return output;
}
x10(a,2)
console.log(a)
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43