Magic eight ball + if/else if

Hi, so i’m doing the Magic eight ball project and i’m stuck. Unfortunately the walkthrough doesn’t show the if/else if method that i’ve used :

let userName = “David”;
console.log(userName ? Hello, ${userName}! : “Hello!”);

let userQuestion = “Will i be able to fly in 2024 ?”;

console.log(Hello i'm ${userName}. ${userQuestion});

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

let eightBall = “”;

if (randomNumber = 0) {
eightBall = “Do not count on it”;
}
else if (randomNumber = 1){
eightBall = “My sources say no”;
}
else if (randomNumber = 2) {
eightBall = “Outlook not so good”;
}
else if (randomNumber = 3) {
eightBall = “Reply hazy try again”;
}
else if (randomNumber = 4) {
eightBall =“Cannot predict now”;
}
else if (randomNumber = 5) {
eightBall = “Signs point to yes”;
}
else if (randomNumber = 6) {
eightBall = “It is decidedly so”;
}
else {
eightBall = “It is certain”;
}

console.log(eightBall);

So, here the final result only shows the first eightBall value after the 0 one. So with this code it shows “My sources say no” (but the random number generated above changes).

If i make the code like this (adding a comment around the else if number 1 :

let userName = “David”;
console.log(userName ? Hello, ${userName}! : “Hello!”);

let userQuestion = “Will i be able to fly in 2024 ?”;

console.log(Hello i'm ${userName}. ${userQuestion});

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

let eightBall = “”;

if (randomNumber = 0) {
eightBall = “Do not count on it”;
}
/else if (randomNumber = 1){
eightBall = “My sources say no”;
}
/
else if (randomNumber = 2) {
eightBall = “Outlook not so good”;
}
else if (randomNumber = 3) {
eightBall = “Reply hazy try again”;
}
else if (randomNumber = 4) {
eightBall =“Cannot predict now”;
}
else if (randomNumber = 5) {
eightBall = “Signs point to yes”;
}
else if (randomNumber = 6) {
eightBall = “It is decidedly so”;
}
else {
eightBall = “It is certain”;
}

console.log(eightBall);

Its show only “Outlook not so good”, and so on…

To preserve code formatting in forum posts, see: [How to] Format code in posts

   =    is used for assignment.

   ==    is used for comparisons.

// You wrote:
if (randomNumber = 0) {
...

// It should be:
if (randomNumber == 0) {
...

// and so on for the rest of the conditions

The condition    if (randomNumber = 0)    isn’t comparing randomNumber with 0. Instead it is assigning the value 0 to randomNumber. Since 0 is a falsy value (Falsy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN), so this condition doesn’t evaluate to true.

The condition    else if (randomNumber = 1)    will assign 1 to randomNumber. 1 is a truthy value (Truthy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN). Therefore, this condition will always evaluate to true.

1 Like

Perfectly explained thank you :pray:.

1 Like