简体   繁体   中英

if condition with ternary operator not returning true or false

I am comparing 2 object properties in Nodejs

 if(alteredItem.main != (result.main)?result.main:"NULL"){

I am using debug mode in VSCODE so when I check:

alteredItem.main = "232"
result.main = "232"

So, I am expecting the result of the above condition to be False but my debug console shows that the value is :

"NULL"

If I remove the ternary operator and change the condition to:

if(alteredItem.main != result.main){

this does return false .

Why does it return "NULL" when I use the ternary operator?

You're mixing an if statement and a ternary expression. You should do either/or, but not both:

Option 1:

if(alteredItem.main != result.main){
  return false;
} else {
  return 'NULL'
}

Option 2:

// It's unclear from your question what you're expecting
// the return value to be, this assumes you want to
// return either `false` or `'NULL'`
return alteredItem.main != result.main ? false : 'NULL';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM