Article on Clearing Javascript Arrays (self-answered question)

Article on Clearing Javascript Arrays (self-answered question)
0

#1

Hi all,

I’ve been working on the Tic Tac Toe project and was having issues when trying to get the game reset functionality to work at the end of each game if the opponent went first. Finally, I figured out the issue and it’s related to how to appropriately clear arrays in Javascript. This article got me unstuck:

http://www.2ality.com/2012/12/clear-array.html

My program stores the player and computer moves in an array and checks if either has moves in any of the winning combinations. After each round, I have a function that clears the board and the arrays with the stored moves. However, I was clearing the arrays with the array = [] technique, figuring that this would set the arrays back to empty for the new round. Now, according to this article, this technique actually creates a new empty array with the same variable name. It sounds like this can be a useful way to clear arrays if you are interested in keeping the originally declared array in existence, but given that I am passing these arrays around to a number of functions in my program, I am in fact interested in clearing out the original arrays. Sure enough, clearing out my arrays with array.length = 0 (or, as someone mentions in the comments of the article, with array.splice(0)) did the trick and now my program works correctly.

Anyways, I just wanted to document this in case anyone ran into this same issue with clearing arrays. If any newer learners are struggling to understand this, I highly recommend looking into the concept of “passing by reference” vs. “passing by value” as it relates to Javascript arrays.

Best,
Eric