Home > Software engineering >  confusion on Javascript evaluation
confusion on Javascript evaluation

Time:08-16

const a = 5 

const b =0

Case1:

a || b 

I will get 5

Case2:

if (a || b ){console.log(true)}

true

In side the condition, I will get back true, so the console.log executed

Case3: 

if (false ? '' || 0 : false) {
  console.log('false')
} else {
  console.log('true') // <- this line get executed always
}

But I expected console.log('false') would be executed Because, in boolean 5 or 0 (T or F) => T , So it means true

May I know why I get wrong?

Edit: Sorry that I made some mistakes.

But what if I want 0 is also considered to be truthy in this case. For example, '' || 0 => true ====> then execute console.log('false')?

CodePudding user response:

I just ran your own code in StackOverflow, and it is working as you expected. i.e. we are getting False

Run it again please, In case:3 , only if condition gets executed

[StackOverflow code snoppet runnerRan on Browser

CodePudding user response:

You have a conditional(ternary) operator with false as condition so your code will always go to that else in that operator

We can represented as follows:

let c = null;
//This is the same as c= false ? '' || 0 : false
if (false) {
  c = '' || 0;//we are never going to enter here if the condition is false
} else {
  c = false;
}
if (c) {
  console.log('false')
} else {
  console.log('true')
}

CodePudding user response:

0 and '' (the empty string) are both what are called falsy values in Javascript, in that implicit type conversion evaluates them to false. So, your final case has three possible outcomes: 0 (evaluates to false), '' (evaluates to false), and false (is false). So, obviously, it will evaluate to false in all cases and the else block will run, printing true to the console.

  • Related