Why does the switch work but not the else if part?


#1

I am working on the Magic Eight Ball project right now here:

https://www.codecademy.com/courses/introduction-to-javascript/projects/magic-eight-ball

I created the proper code based on the switch & case conditional statements and it works.

Later in the project it asked me to get more practice and recreate the code using if/else if/else statements.

Two problems occur when I did this.

#1. My second Math.random code seems to only generate “1” and never anything up to 7.

#2. Due to this, the if/else if/else portion of the code doesn’t work.

What did I do wrong here?

Here is my code:

let userName = ‘’;

userName ? console.log(Hello ${userName}!): console.log(‘Hello!’);

let userQuestion = ‘What is the color of the sky’;

console.log(${userName} asked: ${userQuestion});

let randomNumber = Math.floor(Math.random() * 8);

let randomN = Math.floor(Math.random() * 8);

let eightBall = ‘’;

let eightBalltest = ‘’;

switch (randomNumber) {
case 0:
eightBall = (‘It is certain’)
break;
case 1:
eightBall = (‘It is decidedly so’)
break;
case 2:
eightBall = (‘Reply hazy try again’)
break;
case 3:
eightBall = (‘Cannot predict now’)
break;
case 4:
eightBall = (‘Do not count on it’)
break;
case 5:
eightBall = (‘My sources say no’)
break;
case 6:
eightBall = (‘Outlook not so good’)
break;
case 7:
eightBall = (‘Signs point to yes’)
break;
default:
eightBall = (‘No Response Today’)
break;

}

if (randomN = 0) {
eightBalltest = ‘It is certain’;
} else if (randomN = 1) {
eightBalltest = ‘It is decidedly so’;
} else if (randomN = 2) {
eightBalltest = ‘Reply hazy try again’;
} else if (randomN = 3) {
eightBalltest = ‘Cannot predict now’;
} else if (randomN = 4) {
eightBalltest = ‘Do not count on it’;
} else if (randomN = 5) {
eightBalltest = ‘My sources say no’;
} else if (randomN = 6) {
eightBalltest = ‘Outlook not so good’;
} else if (randomN = 7) {
eightBalltest = ‘Signs point to yes’;
} else {
eightBalltest = ‘no response today’;
}

console.log(eightBall)
console.log(eightBalltest)
console.log(randomNumber)
console.log(randomN)


#2

We need to use the === identity comparison.


#3

Thanks! I missed that.

Just after in a quiz I learned that

“=” is when you are assigning a value to a variable, and “===” is when you are making a comparison.

Thanks for the quick reply!