Skip to content Skip to sidebar Skip to footer

Javascript Switch Statement Only Executes The Default Case

I'm new to JavaScript and wrote this short script to choose a random background color for the body of my page, but it only keeps executing the default case. I don't know what's the

Solution 1:

Math.random() * 4 doesn't return 1, 2 or 3, it returns things like

3.4111702758818865
3.9287009509280324
1.1707445457577705
1.5766741186380386
2.6374688586220145

You need to round that, and as you're not including zero, I guess you want to go up, but that would include 4 as well, so who knows

var colNo = Math.ceil( Math.random()*4 ); // 1-4// orvar colNo = Math.floor( Math.random()*4 ); // 0-3

And.... your switch/case is faulty, you need to break when a condition is met

switch (colNo) {
    case1:
        cl.style.background = 'red';
        break;
    case2:
        cl.style.background = 'yellow';
        break;
    case3:
        cl.style.background = 'pink';
        break;
    default:
        cl.style.background = 'orange';
}

FIDDLE

Post a Comment for "Javascript Switch Statement Only Executes The Default Case"