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 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Ā 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 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Ā 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 toĀfalse
Ā 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!
Top comments (0)