cannot read property of type "length" of undefined Javascript

the idea is, when you refresh the page, it picks random colours, and they all get assigned in the 6x6 grid, but I receive an error

Uncaught TypeError: Cannot read property 'length' of undefined
    at pickColor (colorgame.js:30)
    at colorgame.js:3

I'm really new to javascript (1 week actually and I'm not really sure) I have gone around the internet in search of the answer but I can't make sense of it all

var colors = generateRandomColors(6);
var squares = document.querySelectorAll(".square");
var pickedColor = pickColor(colors);
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");

colorDisplay.textContent = pickedColor;

for (var i = 0; i < squares.length; i++){
    squares[i].style.backgroundColor = colors[i]
    squares[i].addEventListener("click", function(){
        var clickedColor = this.style.backgroundColor;
        if (clickedColor === pickedColor){
            messageDisplay.textContent = "Correct!";
            changeColors(clickedColor)
        } else{
            this.style.backgroundColor = "#232323"
            messageDisplay.textContent = "Try Again!"
        }
    })
}

function changeColors(){
    for (var i = 0; i < squares.length; i++){
        squares[i].style.backgroundColor = pickedColor;
    }
}

function pickColor(colors){
    var random = Math.floor(Math.random() * colors.length);
    return colors[random];
}

function generateRandomColors(num){
    var arr = []
    for (var i = 0; i < num; i++){
        arr.push(randomColor())
    }
}

function randomColor(){
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    return "rgb(" + r + "," + g + "," + b + ")";
}
  <h1 id="title">The Great <span id="colorDisplay">RGB</span> Game</h1>

    <div>
        <span id="message"></span>
    </div>
    
    <div id="container">
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
        <div class="square"></div>
    </div>
    

Upvotes: 1

Views: 135

Answers (1)

Tobias W
Tobias W

Reputation: 260

Your function generateRandomColors should return arr. Otherwise its return value will be undefined and hence, does not have a property length.

Upvotes: 4

Related Questions