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
  • 25,247
  • 27
  • 110
  • 174
  • 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_Ogoo
  • 5,926
  • 3
  • 19
  • 37
  • 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_Ogoo 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
  • 787
  • 5
  • 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)
Komal Sakhiya
  • 718
  • 4
  • 9