-2

I am currently having a hard time figuring out how to use multiple conditions for my if-else statements. I can do 1 condition at a time, but multiples are a problem for me. I'm not quite sure where to start with the multiple one as I'm using the HTML form stuff, and I'm not sure where to start with it as well. Any sample code is fine as I would like to learn rather than have people figure everything out for me.

Mikev
  • 2,012
  • 1
  • 15
  • 27
Gene
  • 27
  • 4

1 Answers1

2

Ok, let's start from the beginning.

You agree that this code right here:

if (true)
    console.log('foo');

obviously prints out 'foo' on your console, cause the condition is satisfied (i.e. is true).

Let's try something different now:

if (true && false)
    console.log('bar');

The && in Javascript and most programming languages is the and operator, which evaluates to true only if both the conditions at its left and at its right are true. This means that the code above does not print out 'bar'.

if (true || false)
     console.log('bla');

The || operator, on the other hand, is the or operator, which is true when one of the two conditions (or both) is true. In this case, 'bla' is printed out on your console.

In the end, let's have a look at the ! operator (not): if the condition that follows the operator is true, then it evaluates to false, and viceversa. So writing if (!false) equals if (true).

Now you can apply these simple rules to easily use multiple logical conditions in one if or else branch. Remember the precedence of the logical operators, i.e. which one you have to evaluate first if you have more than one, taking a look here: Which Logic Operator Takes Precedence

Daniele Cappuccio
  • 1,952
  • 2
  • 16
  • 31