JavaScript Logical Operators and Conditionals

JavaScript Logical Operators and Conditionals

In this post, I’ll cover JavaScript logical operators and conditionals. They are a very important part of many coding languages, not just this one. Logic and conditions are pretty much how most programming languages operate. It is very important to understand this idea as most of the coding is based on it.

Comparison Operators

Before I’ll start the notes regarding the logic and conditions, I’d like to refer back to the comparison operators that were discussed in the previous notes post. They will be an important part of the logic in JavaScript.

Comparison operators are used to comparing two values to each other. A comparison expression will always result in a boolean.

Here’s an example:

let x = 5 + 7;

let test1 = x === 12; // true
let test2 = x < 6; // false
let test3 = x !== 99; //true
let test4 = x >= 12; //true

Logical Operators

Logical operators are used to join two or more comparison expressions together.

There are three logical operators that are being used in JavaScript: AND, OR, and NOT. The last one is not very common; however, it can be quite useful in certain situations.

It’s important to note that in JS we write these operators in a certain way:

SyntaxOperatorMeaning
&&ANDIt requires all individual expressions to be true. One false will make the entire expression false.
||ORIt requires only one of the individual expressions to be true. For the entire expression to become false, all individual expressions must be false.
!NOTIt means “the opposite of”.

&&

In the case of AND operator, all of the expressions have to be true. Otherwise, the entire expression will become false. Let’s look at it in this piece of code:

let age = 16;

let isTeenager = age >= 13 && age <= 19; // true

Here we are trying to see whether the person is a teenager. We created a variable age that’s equal to 16 and a boolean isTeenager that’s using two comparisons. Basically, the person has to be between 13 and 19 to be a teenager.

We are comparing whether the variable age falls in that category, and it does. Hence, the expression will resolve as a true expression.

Also, remember that when using the AND operator, if one of the expressions is resolved as false, the entire expression will become false.

Let’s figure out if the person can drive (legally, at least 😅) using this code:

let age = 17;
let hasDriversLicense = false;
let canDrive = age >= 16 && hasDriversLicense; // false

As you can see, in order for a person to be able to drive, they have to be 16 or older and have a valid driver’s license. In our case, the person is 17 (which is more or equal to 16, so true), but they don’t have a driver’s license. it makes the variable canDrive to become false.

||

In the case of OR operator, if any of the expressions turn out to be true, the entire expression will be true. Let’s look at this code as an example:

let name = "Peter Parker";

let isSpiderman = name === "Peter Parker" || name === "Miles Morales"; // true

As you can see from the code above, the variable isSpiderman will turn out to be true because the variable name is equal to “Peter Parker”.

If we want the OR operator to fire up the false statement, all of the individual expressions have to be false:

let cash = 20;
let hasCreditCard = false;
let price = 25;
let canPurchase = cash >= price || hasCreditCard; // false

In the code above we are checking whether a person can buy something that’s worth $25.

They have $20 cash but no credit card. They can only buy that thing if they have at least $25 or they have a credit card. Since both of these expressions are false, the entire expression will be false also.

It’s also possible to use both logical operators in the same expression to create more complicated (and restrictive) operations. Just like here:

let age = 15;
let hasLearnersPermit = true;
let isWithParents = true;
let canDrive = age >=16 || (hasLearnersPermit  && isWithParents && age >= 15); // true

In the code above we are checking whether a person can drive. The information that’s given to us is their age is 15, they have a learner’s permit, and they are with their parents.

This person will be able to drive if they are 16 or older. Otherwise, they have to satisfy 3 criteria: they need to have the permit, with parents and be 15 or older. The hypothetical person satisfies these criteria, so the statement will be true.

!

The operator NOT will return the opposite value.

Let’s take a look at this code:

let isStudent = false;
console.log(isStudent); // false
isStudent = !isStudent;
console.log(isStudent); //true
console.log(!isStudent); //false

In the code above, we give the value false to the variable isStudent. Then we are using the operator NOT to make it true, and then we use that operator to turn it into false again.

Conditionals

Let’s continue the conversation about JavaScript Logical Operators and Conditionals.

Conditionals give us the ability to allow certain blocks of code to execute only when some condition is true.

We usually implement conditionals using an IF/ELSE statement.

This type of statement:

  • Will always start with an IF clause
  • May contain any number of IF ELSE clauses
  • May optionally end with an ELSE clause

An ELSE clause cannot have a condition. It will always be at the end of the IF ELSE clause and act as a default option.

IF/ELSE

An IF statement will allow us to execute the code only if the condition that was set is true.

The condition we set should always be an expression that evaluates true or false.

Let’s look at this code:

let pokemon;
pokemon = "Pikachu";

if (pokemon === "Pikachu") {
   console.log ("Pikachu, I choose you!");
}

The way we can read the code above is: “if Pokemon is Pikachu, then do stuff.”

ELSE IF

An ELSE IF allows us to add another condition to an IF/ELSE statement.

Let’s look at the code below as an example:

let petName = "Loki";

if (petName === "Murdock") {
   console.log("He's an orange cat!");
}
else if (petName === "Loki") {
   console.log("Loki is grey.");
}

ELSE

An ELSE clause always acts as a default option.

An ELSE clause will always be the last part of the IF/ELSE statement. Let’s look at the code below on how to implement it:

let petName = "Rowdy";

if (petName === "Murdock" || petName === "Loki") {
   console.log("Meow!")
}
else {
   console.log("That pet isn't one of my cats..."); // This is the answer we will get
}

As you can see, we gave the variable petName value Rowdy. Because it’s not Murdock or Loki, we will get an answer “That pet isn’t one of my cats…”.

When one of the conditions in the IF/ELSE statement is found to be true, the block of the code will be executed. We will also jump to the end of the IF/ELSE statement.

let userInput = prompt("Which footbal team is the best?");

if (userInput === "Bears") {
   alert("Da Bears...");
}
else if (userInput !== "Packers") {
   alert("That seems okay...");
}
else {
   alert("Go, Pack, Go!");
}

SWITCH/CASE

There’s another conditional topic we need to cover when we are talking about JavaScript logical operators and conditionals. It is SWITCH/CASE.

It is just another way for us to write a condition with a few caveats.

The only thing SWITCH/CASE can do is check for equality. It’s useful for things like menus and cannot be found in every coding language.

Let’s take a look at the code below:

switch(userInput) {
   case "1":
      console.log("Attacking!");
      break;
   case "2":
      console.log("Defending!");
      break;
   case "3":
      console.log("Evading!");
      break;
   default:
      console.log("Whoops, try again!");
      break;
} 

We always have to write “break” after each statement. Because even though there will be a match, the code will continue to be running. “Break” helps to exit out of it.

Conclusion

While we were talking about JavaScript logical operators and conditionals, we covered a few very important things.

Most of the programming is pretty much based on these things. We will always have to be using logic in order to get to a certain conclusion in our code.

Leave a Reply