Jomar Tinga
Jomar Tinga

Reputation: 67

if condition on node js

I'm Getting confused

I tried to have to have a two condition, in the first code I'm getting true answer seems the answer should be false.

var a = 'route 3';
if(a === 'route 1' || 'route 2'){
  console.log('true')
}else{
  console.log('false')
}

on the second code, I have two conditions and the first condition it seems true and the second must be false but i'm getting true answer. base on my understanding if the first condition is false the second condition will not be evaluated. can you enlighten my newbie mind why i'm getting true answered.

var a = 'route 1';
var b = 'route 3';

if(a === 'route 1' || 'route 2' && b === 'route 1' || 'route 2'){
  console.log('true')
}else{
  console.log('false')
}

thank you for the answer :)

Upvotes: 1

Views: 59504

Answers (4)

Jaime Argila
Jaime Argila

Reputation: 446

Problem:

'route2' returns true because there is no comparing ie. a === 'route2' the string will always return true

Solution:

var a = 'route 3';
if(a === 'route 1' || a === 'route 2'){
  console.log('true')
}else{
  console.log('false')
}

Upvotes: 0

Train
Train

Reputation: 3496

In this statement

if(a === 'route 1' || 'route 2' && b === 'route 1' || 'route 2')

the part that sais || 'route 2') will always evaluate to true.

it must be if(a === 'route 1' || (a === 'route 2' && b === 'route 1') || a === 'route 2')

when you evaluate if('route 2') that would check for a value which always evaluates to true. You would have to compare it to something.

Upvotes: 0

NTR
NTR

Reputation: 1355

Changing your first code block to this will fix your problem:

var a = 'route 3';
if(a === 'route 1' || a === 'route 2'){
  console.log('true')
}else{
  console.log('false')
}

The || operator does not work the way you think. What you are saying is: is a equal to route 1? || is route 2... (instead of: is a equals to route 2). The same issue applies to your second example:

var a = 'route 1';
var b = 'route 3';

if(a === 'route 1' || a === 'route 2' && b === 'route 1' || b === 'route 2'){
  console.log('true')
}else{
  console.log('false')
}

More on operators: Javascript operators

Upvotes: 3

George
George

Reputation: 2422

You are forgetting to check if a is equal to 'route 2', when you simply do if('route 2'). After using ||, you still need to explicitly define the next condition, which is a === 'route 2'.

Instead use:

var a = 'route 3';
if(a === 'route 1' || a === 'route 2'){
  console.log('true')
}else{
  console.log('false')
}

Or even more concise:

var a = 'route 3';
console.log(a === 'route 1' || a === 'route 2');

Upvotes: 1

Related Questions