Search code examples
javascriptjquerygoogle-chrome-console

array.push() method is not adding anything to array and working weirdly


I am new to programming and also stackoverflow. My problem is related to array.push() method in JavaScript. See the code first

var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern = gamePattern.push(nextSequence());

function nextSequence(){
        var randomNumber = Math.floor( Math.random() * 4);
        var randomChosenColor = buttonColors[randomNumber];
        return randomChosenColor;
}

Kindly check this image too... This is chrome console output

The problem is that the randomNumber is being generated properly and randomChosenColor is also getting the color properly but it is not being pushed in gamePattern array at line number 3. Also help me if there is some alternative to this method.


Solution

  • Push changes the original state of the array. So you don't need to re-initialize the array.

     var buttonColors = ["red", "blue", "green", "yellow"];
        let temp=[];
        temp.push(seq());
        console.log(temp);
        function seq(){
            var randomNumber = Math.floor( Math.random() * 4);
            var randomChosenColor = buttonColors[randomNumber];
            return randomChosenColor;
        }