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