title: Javascript rgb color guessing game
body: <p>Why is the first code working but not the second one? it says "Uncaught TypeError: Cannot read property 'style' of undefined
      at HTMLDivElement."</p>
  
  <p>all the squares are div and are declared in the code already.</p>
  
  <pre><code>var colors=[
      "rgb(255, 0, 0)",
      "rgb(255, 255, 0)",
      "rgb(255, 0, 255)",
      "rgb(25, 50, 0)",
      "rgb(2, 0, 50)",
      "rgb(255, 60, 0)"
  ]
  
  var squares= document.querySelectorAll(".square");
  
  var pickedColor=colors[3];
  
  var colorDisplay= document.getElementById("colorDisplay");
  
  colorDisplay.textContent= pickedColor;
  
  for(var i=0; i&lt;squares.length; i++){
      squares[i].style.backgroundColor = colors[i];
      squares[i].addEventListener("click", function(){
          alert(this.style.backgroundColor);
      }); 
  
  
  }
  </code></pre>
  
  <hr>
  
  <pre><code>var colors=[
      "rgb(255, 0, 0)",
      "rgb(255, 255, 0)",
      "rgb(255, 0, 255)",
      "rgb(25, 50, 0)",
      "rgb(2, 0, 50)",
      "rgb(255, 60, 0)"
  ]
  
  var squares= document.querySelectorAll(".square");
  
  var pickedColor=colors[3];
  
  var colorDisplay= document.getElementById("colorDisplay");
  
  colorDisplay.textContent= pickedColor;
  
  for(var i=0; i&lt;squares.length; i++){
      squares[i].style.backgroundColor = colors[i];
      squares[i].addEventListener("click", function(){
          alert(squares[i].style.backgroundColor);
      }); 
  
  }
  </code></pre>