Amir
Amir

Reputation: 335

JavaScript if statement does not work

I have an if statement in JS. when I set the value a == 50, it does not say a is equal to 50. instead it say a is greater than 50. How should I fix this?

Upvotes: -1

Views: 268

Answers (3)

Jack jdeoel
Jack jdeoel

Reputation: 4584

if condition format is if(cond) {} ! no semicolon. Try with ternary also to see how it work ..

var a = 50;
alert(a < 50 ? "a is less than 50" : (a == 50) ? "a is equal to 50" : " a is greater than 50");

Ternary work as

condition ? true : false ;

Upvotes: 0

Washington Guedes
Washington Guedes

Reputation: 4365

You have a typo in this line:

if (a == b); {
//         ^

Remove the semicolon ; after the if-condition:

if (a == b) {

There are two problems with the above if:

  1. b seems to be undeclared.

  2. Your alert says a is equal to 50. But it will never happens inside the if (a < 50) {.


You should use:

var b = 50;

if (a < b) {
    alert ("a is less than " + b);
} else if (a == b) {
    alert ("a is equal to " + b);
} else {
    alert ("a is greater than " + b);
}

Upvotes: 4

Kalpesh Rajai
Kalpesh Rajai

Reputation: 2056

Your condition is wrong just change the you first if condition

if(a<=50){
}

and also remove the ; from the if condition. after that you are ready to go.

if you check the condition like this a<50 so the if condition block only execute when a value is 49 or less than so you never get the message like the a is equal to 50.

Upvotes: 0

Related Questions