Early patterns for functions

Hi guys,
at this lesson

my question is
why isn’t it possible to type it like this?

if (a || b <0) {
  return undefined;
}

instead of

if (a <0 || b <0) {
  return undefined;
}

since they have the same result, was wondering, thanks.

Its just syntax I guess.
The same applies in mathematics after all

3 * 4 + 5 !=  3 * ( 4 + 5 )

In this case the || and && operators need conditionals that evaluate to true or false on either side of them.
That is my understanding at least.
!EDIT! truthiness is not the same as true or false, see [nhcarrigan]'s explanation below

1 Like

Hey there,

The conditions within an if statement are evaluated for truthiness.

If we look at a < 0, with some values for a:

  • if a is 3, then 3 < 0 which is false
  • if a is -3, then -3 < 0 which is true.

With your above proposal of a || b < 0, we get into a tricky bit. The expressions on each side of an || operator are evaluated independently.

So you are checking for at least one of the following to be truthy:

  • a
  • b < 0

The “gotcha” here is that any number value is considered truthy except 0. So where we had a < 0 being false if a had a value of 3, here we’d have a being true (because 3 is a truthy value).

2 Likes

Thanks for your explanation , it makes sense.

1 Like