Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting clear with special conditional statement

Tags:

javascript

I will show you a little part of my app where I am wondering which is the proper way to put a conditional I am working on. If both ways I will show you are correct, I would like you to tell me the consequences/adversities

if ((some.thing === '' || 0) || (some.how === '' || 0)) {
      //something is going on here
}

that is how I have it so far, is there something bad with it?

or should be better this way:

if ((some.thing === '' || some.thing === 0) || (some.how === '' || some.how === 0)) {
       //something is going on here
}

so what are your suggestions ? is it the same result at the end?

EDIT

Adding another way:

if (some.thing === '' || some.thing === 0 || some.how === '' || some.how === 0) {
       //something is going on here
}
like image 558
Non Avatar asked Jun 17 '15 23:06

Non


People also ask

What is an example of a conditional statement?

Example: We have a conditional statement If it is raining, we will not play. Let, A: It is raining and B: we will not play. Then; If A is true, that is, it is raining and B is false, that is, we played, then the statement A implies B is false.

How do you write an if-then formula in Excel with multiple criteria?

Another way to get an Excel IF to test multiple conditions is by using an array formula. To complete an array formula correctly, press the Ctrl + Shift + Enter keys together. In Excel 365 and Excel 2021, this also works as a regular formula due to support for dynamic arrays.


2 Answers

The || operator has precedence over the comparison operators.

So some.thing === '' || 0 is the same as (some.thing === '') || (0). It:

  • will evaluate to 0 if some.thing === '' is false or
  • will evaluate to true if some.thing === '' is true.

Look at this example (as running in a JavaScript console):

> some = { thing: 0 }
  Object { thing: 0 }
> some.thing === ''
  false
> some.thing === '' || 0  // this is like false || 0
  0
> some = { thing: '' }
  Object { thing: "" }
> some.thing === ''
  true
> some.thing === '' || 0  // this is like true || 0
  true

Prefer something like the last expression you wrote.

EDIT: Actually both '' and 0 are falsy in JavaScript, so you can just simply write your complete expression as:

if (!some.thing || !some.how) {
  //something is going on here
}
like image 126
ericbn Avatar answered Oct 21 '22 10:10

ericbn


This part looks fishy to me:

some.thing === '' || 0

Do you mean this instead:

some.thing === '' || some.thing === 0

0 is always falsy, so the expression some.thing === '' || 0 is always equivalent to some.thing === ''

EDIT

You need the final expression:

(some.thing === '' || some.thing === 0 || some.how === '' || some.how === 0)
like image 36
Andrew Eisenberg Avatar answered Oct 21 '22 11:10

Andrew Eisenberg