-3

I have a variable arg and it has been assigned as follows

arg = [...arg]; 

What does this assignment mean ?

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
MindBrain
  • 7,398
  • 11
  • 54
  • 74
  • 4
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator – willwoo Dec 11 '17 at 21:39
  • 1
    While the above documentation may explain the spread operator, I think OP is asking something slightly more specific - *"Why assign a variable **to itself** with a spread operator?"* – Tyler Roper Dec 11 '17 at 21:41
  • 1
    i mean... we could tell you what that does, but is that really what you are asking? because that's pretty obvious given the documentation on the subject or a few console.logs. – Kevin B Dec 11 '17 at 21:42
  • The significance is that whoever wrote this needs to learn how to write clearer code. – Nathan Jones Dec 11 '17 at 21:44
  • Yes, I wanted to ask if the array has been filtered as follows args.forEach((Item: any) => {...} . followed by args= [...args]; What is the significance of the args = [...args] ? – MindBrain Dec 11 '17 at 21:45
  • Last comment is as vague as your initial question – charlietfl Dec 11 '17 at 21:45

1 Answers1

-3

Assuming the original arg is an array

What happens here is best demonstrated using an example

const x = [1,2,3,4];
const y = [...x];
x == y; // false
x === y; // false
x[0] == y[0]; // true
x[0] === y[0]; // true

So while the content of the array has remained identical, the array itself is another reference. So this created a copy of the array so the original array is not modified.

An example of this can be in a method

function example1(x) {
  x = [...x];
  x[0] = 0;
  return x;
}
function example2(x) {
  x[0] = 0;
  return x;
}

const a = [1,2,3];
console.log(a);
const b = example1(a);
// The input variable is not mutated
console.log(a); // [1,2,3]
console.log(b); // [0,2,3]
const c = example2(a);
// The input variable is mutated as well
console.log(a); // [0,2,3]
console.log(c); // [0,2,3]
Rogier Slag
  • 526
  • 3
  • 7
  • 1
    Based on the question, there is quite some room for guessing. For a code quality perspective it does not seems right to spread an string into an array like this. The most probably use case would be to quickly create a copy of an array to prevent touching the original reference – Rogier Slag Dec 11 '17 at 21:52
  • 1
    Yeah, I had removed my comment upon realizing. That being said, I haven't downvoted - though I have a hunch that it may be because you've submitted a "guess" as an answer (as you yourself have acknowledged). – Tyler Roper Dec 11 '17 at 21:53