JavaScript Conditionals — Rabbit Hole Edition

First, what is a conditional statement?

Conditional statements are used to perform different actions based on different conditions.

We use this system of reasoning, presumably, every day in everyday decisions. I find that I use it most in strategic thinking. Whether it be designing a 5-year plan with pandemic contingencies, or a game strategy for Settlers of Catan or the like.

This system of reasoning can also be referred to as:

Logic

What is logic?

The study of principles of reasoning, especially of the structure of propositions as distinguished from their content and of method and validity in deductive reasoning.

Who Says?

Aristotle’s collection of his teachings, known as the Organon (4th century BCE) is the earliest extensive writing on the subject of logic.

To ancient Greeks, logic was a means of analyzing language in search for truth and thus was considered a form of philosophy.

For over 2,000 years mathematicians wrestled with Aristotle’s logic, attempting to corral it using mathematical symbols and operators.

Prior to the 19th century, the only person to come close to encapsulating this concept mathematically was Gottfried Wilhelm von Leibniz (1648–1716). Gottfried was a German philosopher, mathematician, scientist, diplomat and polymath, who dabbled with logic early in life but then went on to pursue other interests*.

* Such as independently developing the concepts of differential and integral calculus during the same time as Isaac Newton.

If you want the tea, read here to learn more about this very real calculus controversy.

100 years later in 1815 in England, George Boole was born.

Who is George Boole?

George Boole was a largely self-taught English mathematician, philosopher and logician, born in 1815.

He was the son of a shoemaker and a former maid. Britain’s rigid class system would have normally prevented him from achieving anything different from his ancestors.

Aided with an inquisitive mind and his helpful father (who had strong interests in science, mathematics, and literature), George gave himself the type of education normally exclusive to the privilege of upper-class boys.

It was Boole’s genius to make algebra more abstract by divorcing it from concepts of number.

This was ground-breaking.

I’ll get to them in a minute.

Now, algebra could account for not only numbers, but classes.

What is a class?

A class is a group of things. To demonstrate what this means, we will talk about what classes can do using mathematical operators.

Union(+)

In boolean algebra the operator ‘+’ indicates a union of two classes. A union of two classes is everything in the first class combined with everything in the second class.

Exercise

In the following example, assume there are two classes. One class of black cats, which we will represent with ‘B’, and a class of white cats, ‘W’.

A. this cat is neither a black cat, or a white cat.

Explanation

Options B and C are both examples of the expression ‘B + W’, or a union of the two classes. In both images there are one or more cats, all of which are monochromatic in either black or white. Option A is not an example of this, as the cat lounging is BOTH black and white. *

Intersection(*)

In boolean algebra, the ‘*’ indicates an intersection of two classes. An intersection of two classes is everything that is in both the first class and the second class.

Exercise

In this example, we are going to add two more classes. ‘F’, which will represent all cats that are female, and ‘T’, which will represent all cats that are tan.

Explanation

The expression ‘B * W’ represents an intersection of black and white cats. This means ‘All cats that are black AND white’. Our cat from the previous exercise is a perfect example of a ‘B * W’ cat. Below is a tan cat, who for this exercise we will assume is female in gender. She is representative of all ‘F * T’ cats, or — all tan cats that are female.

Boolean Algebra to JavaScript

In JavaScript, we can apply the concepts of boolean algebra to write code that can make decisions for us!

For this we need to develop an understanding of the following concepts:

  • Control Flow
  • Conditional Statements
  • Comparison Operators
  • Logical Operators

Control Flow

Control flow is the order in which statements are executed in a program.

The default control flow for statements to be read and executed in order is from left-to-right, top-to-bottom in a JavaScript file.

Control structures, such as conditional statements, alter control flow by only executing blocks of code if certain conditions are met.

These structures essentially allow a program to make decisions which code is executed as the program runs.

Conditional Statements

Conditional statements provide us with flow control to determine the output of our programs. There are three conditional statements in JavaScript:

Lets go over each of these conditional statements breaking them down to two parts: the statement and the structure.

1. If

Statement

This is the most common type of conditional. Use the ‘if’ statement to specify a block of JavaScript code to be executed if a condition is true. All values are true UNLESS they are defined as falsy.

Structure & Syntax

if (condition === true) {
// block of code to be executed if the condition is true
}
  • The if keyword followed by a set of parentheses (), which is followed by a code block, or block statement, indicated by a set of curly braces {}.
  • The parentheses wrap a condition that evaluates to true or false.
  • If the condition evaluates to true, the code inside the curly braces {} runs, or executes.
  • If the condition evaluates to false, the block won’t execute.

Exercise

Make a ‘good day’ greeting if the hour is less than 18:00 :

if (hour < 18) {
greeting = "Good day";
}

2. Else

Statement

This conditional is always used in conjunction with an ‘if’ ‘statement — this is called an ‘if…else’ statement. Use the ‘else’ statement to specify a block of JavaScript code to be executed if a condition is ‘false’. The difference between an ‘if’ and an ‘if…else’ statement is that ‘if…else’ statements account for both *truthy* and *falsy* return values. ‘if…else’ statements allow us to automate solutions to yes-or-no questions, also known as binary decisions.

Structure & Syntax

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
  • Uses the ‘else’ keyword following the code block of an ‘if’ statement.
  • Has a code block that is wrapped by a set of curly braces {}.
  • The code inside the ‘else’ statement code block will execute when the ‘if’ statement condition evaluates to false.

Exercise

If the hour is less than 18, create a ‘Good day’ greeting, otherwise ‘Good evening’ :

if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good Evening";
}

3. Else If

Statement

The else if statement allows for more than two possible outcomes. An else/if statement doesn’t need a following ‘else’ statement to work. The else if statement always comes after the if statement and before the else statement. The else if statement also takes a condition.

Structure & Syntax

if (condition) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if condition2 is true
} else {
// block of code to be executed if condition1 and condition2 evaluate to false.
}

Exercise

If time is less than 10:00, create a ‘Good morning’ greeting, if not, but the time is less than 20:00, create a ‘Good day’ greeting, otherwise a ‘Good evening’ :

if(time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}

Comparison Operators

  • Comparison operators are used when comparing two values and returns true or false depending on the validity of the comparison.
  • Comparison operators compare the value on the left with the value on the right.
  • All comparison statements evaluate to either true or false.

Logical Operators

Working with conditional statements means that we will be using booleans — which return either true or false values. In JavaScript, there are operators that work with boolean values known as ‘logical operators’. These can be used to add more sophisticated logic to conditional statements.

&&

“and” Operator

When using the ‘&&’ operator, both conditions must evaluate to ‘true’ for the entire condition to evaluate to ‘true’ and thus execute the proceeding code block.

let mood = 'sleepy';
let tirednessLevel = 6;
if (mood === 'sleepy' && tirednessLevel > 8) {
console.log('time to sleep');
} else {
console.log('not bed time yet.');
}

||

“or” Operator

Similar to the ‘and’ operator, the ‘or’ operator is checking multiple conditions. The difference between the two is that an ‘or’ operator only cares if one of the conditions evaluates to true, whereas the ‘and’ operator will only execute the proceeding code block if both conditions evaluate to true. When using the ‘or’ operator, only one of the conditions must evaluate to ‘true’ for the overall statement to evaluate to ‘true’.

if (day === 'Saturday' || day === 'Sunday') {
console.log('Enjoy the weekend!');
} else {
console.log('Do some work.');
}

!

“bang” Operator

This is a fun one. Essentially, the ‘!’ operator will take a ‘true’ value and passes back ‘false’.

let excited = true;
console.log(!excited); // prints false
let sleepy = false;
console.log(!sleepy); // prints true

Truthy and Falsy

Let’s consider how non-boolean data types, like strings and numbers, are evaluated when checked inside a condition.

Sometimes, you will want to check if a variable exists and you won’t necessarily want it to equal a specific value — you’ll only check to see if the variable has been assigned a value. Since it is more succinct to explain in terms of what isn’t true, below is a list of all the falsy values in JavaScript.

  • false
  • 0
  • empty strings, ‘’
  • null
  • undefined
  • NaN

Software Engineer