Lyudvig Bodmer
Lyudvig Bodmer

Reputation: 11

Please help to find out why the code works in such manner (JavaScript)

i've been working on a primitive code and got the unexpected result.

var one = prompt("Enter the number", "4");
var age = parseInt(one);
if (age >= 14 || age <= 90) {
    console.log("Correct");
} else {
    console.log("Wrong")
}

When I put 100, for example, it says "Correct" instead of "Wrong".

Would you be so kind to answer why it works in such manner.

Upvotes: 0

Views: 49

Answers (3)

Usama Qureshi
Usama Qureshi

Reputation: 81

I got ur Requirement instead of Using OR Operator i.e "||" you should use AND Operator i.e "&&" then u will get the desired result its a logical error

Upvotes: 0

blex
blex

Reputation: 25634

Any number will return true, because any number is > 14 OR < 90.

If you need the age to be between 14 and 90, do it this way:

if ( age >=14 && age <= 90 )

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You are using an or operation, so when age is 100 the first part of the OR operation is true which means that the entire OR condition is true because true OR false is true.

You need to use and AND operator

var one = prompt("Enter the number", "4");
var age = parseInt(one);
if (age >= 14 && age <= 90) {
    console.log("Correct");
} else {
    console.log("Wrong")
}

Upvotes: 1

Related Questions