Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my variable getting undefined in javascript?

I’m working on some code that first pulls a random number between 1-6 (getRand6).

Then it loops through a while statement as many times as whatever number is pulled for getRand6. Each cycle of the loop pulls a color based on another random number between 1-10 (getRand10).

It then creates an html paragraph with the color name and adds it to allColors, and then subtracts 1 from getRand6.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

When getRand6 is 0, it exits the while loop and posts allColors to an object with the id "colors".

Everything seems to be working, but along with the color names I’m getting an "undefined" at the beginning of allColors. E.g. The rough page code would show a something like:

undefined
<p>Red</p>
<p>Green</p>
<p>Red</p>
<p>Blue</p>

I’m sure this is a simple thing that I’m overlooking, but I’m still kinda new to all this and would love the help.

getRand6 = Math.floor(Math.random()*6) + 1;
var allColors;
while (getRand6 > 0) {
    getRand10 = Math.floor(Math.random()*10) + 1;

    if (getRand10 > 0 && getRand10 < 4) {specColor = "Red";}
    else if (getRand10 > 3 && getRand10 < 7) {specColor = "Green";}
    else if (getRand10 > 6 && getRand10 < 10) {specColor = "Blue";}
    else {specColor = "White";};

    allColors += "<p>" + specColor + "</p>";

    getRand6--;
}
document.getElementById ('colors').innerHTML = allColors;

>Solution :

Just change this

var allColors;

Into this

var allColors="";

Your probleme is that your using += with allcolors but in first time allcolor is undefined

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading