If, else if, else question

Hello,

JS novice here : )

kindly see my code

var fish = 20;

        if (fish > 25){

            alert("some fish");

        }else if (fish = 30) {

            alert("more fish");

        }else  alert("remaining");

when it runs the else if displays though 20 fish doesn’t equal 30

shouldn’t my else be displayed?

do you see what i mean?

the code runs fine when i replace the = with > or <

confused : (

In your else condition, you are using an assignment which is always successful, instead of a comparison.

2 Likes

Hi @OBXjuggler, this is an assignment not an equality check; and an assignment evaluates to the value being assigned, so you’re effectively checking else if (30) which will always pass if the previous condition doesn’t. So it should be something like:

if (fish > 25 && fish < 30) {
  // ...
} else if (fish === 30) {
  // ...
} else {
  // ...
}

Edit: Beaten by @Paul_Wilkins . :-)

5 Likes

many thanks!

something new to learn!

do i owe you a $0.25 now?

1 Like

A virtual chocolate fish is traditional :slight_smile:

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.