DEV Community

Pepe Benitez
Pepe Benitez

Posted on

Boolean Logic in Javascript šŸ¤“

Hi! Programming can be overwhelming šŸ˜« but once you are comfortable with some basic concepts, it starts to feel like a superpower šŸ¦øā€ā™€ļø 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!
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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!');
}
Enter fullscreen mode Exit fullscreen mode

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.')
}
Enter fullscreen mode Exit fullscreen mode

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!'
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

'apples' === 'oranges' // false
Enter fullscreen mode Exit fullscreen mode

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 samenes

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

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');
}
Enter fullscreen mode Exit fullscreen mode
  • 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.');
}
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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++;
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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!');
}
Enter fullscreen mode Exit fullscreen mode

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

isNightTime ? console.log('Turn on the lights!') : console.log('Turn off the lights!');
Enter fullscreen mode Exit fullscreen mode
  • 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!

Top comments (0)