This content originally appeared on DEV Community and was authored by Pepe Benitez
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!
Notice in the example above, we have an if
statement. 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 totrue
orfalse
. - 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 if
statement, 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 anif
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 theif
statement’s condition evaluates tofalse
.
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 false
when 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 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');
}
- 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:
- an initialization starts the loop and can also be used to declare the iterator variable.
- 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 tofalse
the code will stop. - 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 Tutorial: Learn JavaScript For Free | Codecademy
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!
This content originally appeared on DEV Community and was authored by Pepe Benitez
Pepe Benitez | Sciencx (2021-06-02T15:48:59+00:00) Boolean Logic in Javascript ?. Retrieved from https://www.scien.cx/2021/06/02/boolean-logic-in-javascript-%f0%9f%a4%93/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.