Boolean Logic in Javascript šŸ¤“

Ā·

8 min read

Hi! Programming can be overwhelming šŸ˜« but once you are comfortable with some basic concepts, it starts to feel like a super power šŸ¦øā€ā™€ļø and Javascript is one of the coolest languages to learn! šŸ’Æ

In this document you can find a summary of using Boolean Logic in Javascript. We will cover:

  • What are booleans?
  • Conditional Statements
  • Truthy and Falsy values
  • Comparison operators
  • Logical operators
  • Looping

If you need help with your setup, you can find some help here šŸ‘ˆ

What are booleans?

Booleans are part of what we call primitive data types in javascript.

This data type only has two possible valuesā€” either true or false (without quotes). Itā€™s helpful to think of booleans as on and off switches or as the answers to a ā€œyesā€ or ā€œnoā€ question.

Boolean - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

Conditional Statements

if-else decisions can be modeled in code by creating conditional statements. A conditional statement checks a specific condition(s) and performs a task based on the condition(s).

If Statement

In programming, we can perform a task based on a condition using an if statement:

if (true) {
  console.log('This message will print!'); 
}
// Prints: This message will print!

Notice in the example above, we have an ifstatement. The if statement is composed of:

  • 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 {}.
  • Inside the parentheses (), a condition is provided 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.

If..else Statements

If we wanted to add some default behavior to the if statement, we can add an else statement to run a block of code when the condition evaluates to false.

if (false) {
  console.log('The code in this block will not run.');
} else {
  console.log('But the code in this block will!');
}

// Prints: But the code in this block will!

An else statement must be paired with an ifstatement, and together they are referred to as an if...else statement.

In the example above, the else statement:

  • 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ā€™s condition evaluates to false.

if...else statements allow us to automate solutions to yes-or-no questions, also known as binary decisions.

If.. else if.. else Statements

We can add more conditions to our if...else with an else if statement. The else if statement always comes after the if statement and before the else statement. The else if statement also takes a condition.

let stopLight = 'yellow';

if (stopLight === 'red') {
  console.log('Stop!');
} else if (stopLight === 'yellow') {
  console.log('Slow down.');
} else if (stopLight === 'green') {
  console.log('Go!');
} else {
  console.log('Caution, unknown!');
}

The else if statements allow you to have multiple possible outcomes. if/else if/else statements are read from top to bottom, so the first condition that evaluates to true from the top to bottom is the block that gets executed.

Truthy and Falsy Values

Sometimes, youā€™ll 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.

let myVariable = 'I Exist!';

if (myVariable) {
   console.log(myVariable)
} else {
   console.log('The variable does not exist.')
}

The code block in the if statement will run because myVariable has a truthy value; even though the value of myVariable is not explicitly the value true, when used in a boolean or conditional context, it evaluates to true because it has been assigned a non-falsy value.

So which values are falsyā€” or evaluate to falsewhen checked as a condition? The list of falsy values includes:

  • 0
  • Empty strings like "" or ''
  • null which represent when there is no value at all
  • undefined which represent when a declared variable lacks a value
  • NaN, or Not a Number
let numberOfApples = 0;

if (numberOfApples){
   console.log('Let us eat apples!');
} else {
   console.log('No apples left!');
}

// Prints 'No apples left!'

Truthy and Falsy Assignment

In a boolean condition, JavaScript assigns the truthy value to a variable if you use the || operator in your assignment:

let defaultName = username || 'Stranger';

Because || or statements check the left-hand condition first, the variable defaultName will be assigned the actual value of username if is truthy, and it will be assigned the value of 'Stranger' if username is falsy. This concept is also referred to as short-circuit evaluation.

Comparison Operators

When writing conditional statements, sometimes we need to use different types of operators to compare values. These operators are called comparison operators.

Here is a list of some handy comparison operators and their syntax:

  • Less than: <
  • Greater than: >
  • Less than or equal to: <=
  • Greater than or equal to: >=
  • Is equal to: ===
  • Is not equal to: !==

Comparison operators compare the value on the left with the value on the right.

10 < 12 // Evaluates to true

We can also use comparison operators on different data types like strings

'apples' === 'oranges' // false

All comparison statements evaluate to either true or false and are made up of:

  • Two values that will be compared.
  • An operator that separates the values and compares them accordingly (>, <, <=,>=,===,!==).

Comparisons and sameness

In javascript we use === to compare elements. == can also work but it is not strict (it does not compare data types)

Read more here šŸ‘‰ Equality comparisons and sameness

Logical Operators

Working with conditionals means that we will be using booleans, true or false values. In JavaScript, there are operators that work with boolean values known as logical operators. We can use logical operators to add more sophisticated logic to our conditionals. There are three logical operators:

  • the and operator (&&)

When we use the && operator, we are checking that two things are true

if (stopLight === 'green' && pedestrians === 0) {
  console.log('Go!');
} else {
  console.log('Stop');
}
  • the or operator (||)

If we only care about either condition being true, we can use the || operator

if (day === 'Saturday' || day === 'Sunday') {
  console.log('Enjoy the weekend!');
} else {
  console.log('Do some work.');
}
  • the not operator, otherwise known as the bang operator (!)

The ! not operator reverses, or negates, the value of a boolean

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

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

Looping

We can use booleans, or statements that evaluate to booleans, to run loops for a set of defined values, like the elements of an array or a range of numbers, or while a condition evaluates to true. We can user For loops and While loops respectively.

The For Loop

The typical for loop includes an iterator variable that usually appears in all three expressions. The iterator variable is initialized, checked against the stopping condition, and assigned a new value on each loop iteration. Iterator variables can have any name, but itā€™s best practice to use a descriptive variable name.

A for loop contains three expressions separated by ; inside the parentheses:

  1. an initialization starts the loop and can also be used to declare the iterator variable.
  2. a stopping condition is the condition that the iterator variable is evaluated againstā€” if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop.
  3. an iteration statement is used to update the iterator variable on each loop.

The for loop syntax looks like this:

for (let counter = 0; counter < 4; counter++) {
  console.log(counter);
}

The While Loop

We start our loop with the keyword while followed by our stopping condition, or test condition. This will be evaluated before each round of the loop. While the condition evaluates to true, the block will continue to run. Once it evaluates to false the loop will stop.

// A while loop that prints 1, 2, and 3
let counterTwo = 1;
while (counterTwo < 4) {
  console.log(counterTwo);
  counterTwo++;
}

The syntax of a for loop is ideal when we know how many times the loop should run, but we donā€™t always know this in advance. In situations when we want a loop to execute an undetermined number of times, while loops are the best choice.

Do...While Statements

A do...while statement says to do a task once and then keep doing it until a specified condition is no longer met. The syntax for a do...while statement looks like this:

let countString = '';
let i = 0;

do {
  countString = countString + i;
  i++;
} while (i < 5);

console.log(countString);

First, the code block after the do keyword is executed once. Then the condition is evaluated. If the condition evaluates to true, the block will execute again. The looping stops when the condition evaluates to false.

Note that the while and do...while loop are different! Unlike the while loop, do...while will run at least once whether or not the condition evaluates to true.

Bonus

Ternary Operator

In the spirit of using short-hand syntax, we can use a ternary operator to simplify an if...else statement.

let isNightTime = true;

if (isNightTime) {
  console.log('Turn on the lights!');
} else {
  console.log('Turn off the lights!');
}

We can use a ternary operator to perform the same functionality:

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
  • The condition, isNightTime, is provided before the ?.
  • Two expressions follow the ? and are separated by a colon :.
  • If the condition evaluates to true, the first expression executes.
  • If the condition evaluates to false, the second expression executes.

Like if...else statements, ternary operators can be used for conditions which evaluate to true or false.

Useful resources on Javascript

JavaScript | MDN

freeCodeCamp.org

JavaScript Tutorial: Learn JavaScript For Free | Codecademy

JavaScript Code to go


Hi! My name is Pepe šŸ‘¾, and I am from Panama in Central America šŸŒ“šŸŒžšŸŒ“ You can find me in linkedin, twitter or github.

  • If you found this useful feel free to share it!
  • If you have any questions, recommendations or general comments feel free to drop me a message!