30 Days Of JavaScript

Day 3: Logic

Lesson 3: The OR operator

The companion to the 'AND' operator && is the 'OR' operator ||. The result of the 'AND' test will be true if the items either side of it are true, the result of the 'OR' operator will be true if any or both of the things either side of it are true.

Let's take a look at an example.

In this case our intrepid coder knows JavaScript and so can call themselves a developer. If they knew Python as well or instead then they would also be able to say they are a developer, sadly if they know neither then, at least in this test, they are not a developer.

Shortcut

In the 'OR' example the constants being tested are booleans (we know this because we set them to true and false), so we actually don't need to do === true. Because under the hood all of these operators like < and === are applying a test (is less than, is equal to) to the items either side of them and then giving you the result as a boolean. If the things being compared by the 'OR' || or the 'AND' && test are booleans already then we don't need the step we have in the above example.

So we can do this instead:

This leads to an easier to read and easier to maintain codebase, it is also considered best practice. However in the short term you may find this short hand method a little confusing, if you want to keep being explicit by testing === true or === false then that's totally cool.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co