-2

I have some problems understanding this code, maybe I'm missing some basics...

JS:

const grid = document.querySelector('.grid')
let squares = []

function createGrid() {
    //create 100 elements with a for loop
    for (let i=0; i < 100; i++) {

    const square = document.createElement('div')

    square.classList.add('square')

    grid.appendChild(square)

    squares.push(square)
    }
}

squares[10].classList.add('snake') //magic happens

CSS:

.snake {
    background-color: green;
}

How come squares array elements affect dynamically on square. (squares[0].classList.add('snake'))?

Why putting style on array elements would affect the created elements?

squares should be a "static" array?

Thanks...

Sarun UK
  • 6,210
  • 7
  • 23
  • 48
  • Because JS passes objects by reference … https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference – CBroe Nov 24 '20 at 09:38

1 Answers1

0

How come squares array elements affect dynamically on square.

Appending an element somewhere in the DOM doesn't remove it from the array.

The array continues to hold a reference to the DOM element.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335