Tic tac toe React.js

I don’t understand this code in time travel code const current = history[history.length - 1] . What does that mean? and why it’s not just history.length.

Hi @HaithamCa !

The code means to grab the last element in the array.

For example,

const arr = [1,2,3,4]

So arr[arr.length -1] would be index 3.
At index 3 we have the number 4.

Hope that makes sense!

1 Like

Hello there,

This is a very common practice to see in programming. Seeing as many programming languages (including JavaScript) are zero-indexed, to access the first element of an array, you need to get the 0 index:

const myArr = [1, 2, 3, 4];

Now, if I wanted the last element, I would need myArr[3], as this is the fourth element at index 3 of the array.

So, running this code would produce unwanted results:

const myArr = [1, 2, 3, 4];
console.log(myArr[myArr.length]); // returns undefined

Because the length of myArr is 4, but there is no element at index 4.

Hope this helps


Thanks, it’s clear now. But unfortunately, I still confused in another part at the same code
const winner = calculateWinner(current.squares);. Now, current.squares this code becomes history[the last square I pressed].Array(9).fill(null) . I can’t imagine the logic of this code.

const winner = calculateWinner(current.squares); this code in the React tutorial CalculateWinner is a function return boolean value based who is a winner and current return the last squares I pressed. but what about squares, is that means Array(9).fill(null)?. It doesn’t make sense for me.

Remember to use the READ-SEARCH-ASK methodology.

Have a read of this:
Array() constructor - JavaScript | MDN (mozilla.org)

Hope this helps

Thanks for your response. I did a lot for this small point. :grinning: fortunalely, I find the solution in the next section of the same tutorial, and the problem was in .slice(). Sorry for the inconvenience.