Analysis of the X and O marks alternation

In this lesson, I want to show you how to make an alternation of a cross and a zero in one line. You most likely did something like this:

function start(cells) { let i = 0; // the counter initial value for (let cell of cells) { cell.addEventListener('click', function() { if (i % 2 == 0) { this.textContent = 'X'; } else { this.textContent = '0'; } i++; // increases the counter value }); } }

I will suggest to solve the problem in a shorter way. Let's make an array of our 'players':

let gamers = ['X', 'O'];

As you can see, in this array, the X mark has the key 0, and the O mark has the key 1. The same can be said about i % 2 - for the X mark the remainder will be 0, and for the O mark - 1.

That is, this thing can be used instead of a key:

let gamers = ['X', 'O']; let key = i % 2; console.log(gamers[key]);

Or even shorter:

let gamers = ['X', 'O']; console.log(gamers[i % 2]);

Or even shorter:

console.log(['X', 'O'][i % 2]);

Let's simplify our start function code:

function start(cells) { let i = 0; for (let cell of cells) { cell.addEventListener('click', function() { this.textContent = ['X', 'O'][i % 2]; i++; }); } }

On your own, without looking into my code, make the described edit.

Now you can make an unlimited number of clicks on any cell, changing, for example, a cross to a zero. Fix it.

enru