1

I'm now studying a course There's one question I don't understand

What is the output of below code using closure?

function createPlayer() {
  let score = 0;

  function add(amount) {
    score = score + amount;
  }

  function report(label) {
    console.log(label, score);
  }

  return {
    score,
    add,
    report,
  };
}

let player1 = createPlayer();
let player2 = createPlayer();

player1.add(1);
player2.add(2);

console.log('1:', player1.score);
console.log('2:', player2.score);

player1.report('3:');
player2.report('4:');

My choice is

1: 1
2: 2
3: 1
4: 2

However , the correct answer is

1: 0
2: 0
3: 1
4: 2

May I ask why player1.score & player2.score are still 0 after the function player1.add(1) & player2.add(2) are called ? Wouldn't the the score be increased by 1 and 2 ?

Please help me solve the problems

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Andy
  • 11
  • 1
  • You copy the values from the variables to the object and return the object before you change the values of the variables. Numbers are copied by value, they aren't references. – Quentin Apr 04 '23 at 10:05
  • 1
    `let score` isn't linked to `{ score, ... }`. You're returning an object with the current value of `score`, not "the variable". – deceze Apr 04 '23 at 10:05
  • Because the `player1.score` property is a different thing than the `let score` variable. Only one of them is updated. – Bergi Apr 04 '23 at 10:05
  • 1
    You can replace score by a getScore function which will return the value of score inside of the closure – Axnyff Apr 04 '23 at 10:06
  • i still dont understand.. – Andy Apr 04 '23 at 10:13
  • @Andy — Write the number 0 on a blackboard. (`let score = 0;`). Take a photo of it and email it to a friend (`return { score }`). Now erase the 0 and write 1 instead (`core = score + amount`). Now look at the photo. It still shows 0. – Quentin Apr 04 '23 at 10:20

0 Answers0