1

I was working on this example yesterday and I was wondering if that spread syntax, (the only one used) has any utility in this case? Given that the array with objects won't change at all with that; or I am mistaken? if it does, how so?

const quiz = [{
    name: "Superman",
    realName: "Clark Kent"
  },
  {
    name: "Wonderwoman",
    realName: "Dianna Prince"
  },
  {
    name: "Batman",
    realName: "Bruce Wayne"
  },
];

const game = {
  start(quiz) {

    //    ----> this \/
    this.questions = [...quiz];
    this.score = 0;
    // main game loop
    for (const question of this.questions) {
      this.question = question;
      this.ask();
    }
    // end of main game loop
    this.gameOver();
  },
  ask() {
    const question = `What is ${this.question.name}'s real name?`;
    const response = prompt(question);
    this.check(response);
  },
  check(response) {
    const answer = this.question.realName;
    if (response === answer) {
      alert('Correct!');
      this.score++;
    } else {
      alert(`Wrong! The correct answer was ${answer}`);
    }
  },
  gameOver() {
    alert(`Game Over, you scored ${this.score} point${this.score !== 1 ? 's' : ''}`);
  }
}

game.start(quiz);
5
  • 2
    It takes a shallow copy of the array. In this particular code there's no need, but it's often good practise not to mutate arrays and/or objects that have been passed to a function unless the specific intention of that function is to perform that mutation. Commented Jan 16, 2019 at 0:31
  • Looks like he's just spreading the elements of quiz into a new array Commented Jan 16, 2019 at 0:31
  • @GrzegorzMiśkiewicz he is using template strings, replacing ` with ' would break the code Commented Jan 16, 2019 at 0:35
  • My mistake - sorry. Commented Jan 16, 2019 at 0:37
  • For completeness: You don't need the spread syntax to clone an array. You can also use arr.slice() or Array.from(arr). Commented Jan 16, 2019 at 6:35

1 Answer 1

3

what you witness here is the copying of an array. Basically JS does this

a = [1,2,3];
b = a;
a.push(4);
// a == b == [1,2,3,4]

but if you want to make a copy so b is not changed when a is you need to do the spread

a = [1,2,3];
b = [...a];
a.push(4);
// a == [1,2,3,4], b == [1,2,3]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.