0

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.

3
  • push returns the number inserted, not the new array. The push happens in-place. Commented May 31, 2020 at 4:36
  • Read this article for tips on debugging your code. Commented May 31, 2020 at 4:40
  • The code you posted does not create the output in the screenshot. If you still need help after debugging your code, please post a minimal reproducible example. Commented May 31, 2020 at 4:42

2 Answers 2

1

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;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank You Brother, you have solved my problem. Please tell me what is this "let" keyword that you have added
"let" keyword is used for variable declaration it is block scoped . To read about it more . You can refer this document developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
0

push() mutates the original array (and returns the new length), so you don't need to assign a new value to gamePattern. Try something like this:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.