When you are programming in Javascript. The lines of code are executed line by line. In order to create useful programs, we will need to learn to intercept this flow of execution and go another direction or even restart in the same direction.
This is referred to control flow and is made up of a combination of operators, conditionals and/or loops. Let's take a look at how these parts help to control the flow in your Javascript code.
Operators
Operators are tests for the truth or false values of variables.
Userful Operators
operator: == description: equal to
const x = 11
x == 11
// returns true
operator: === description: equal value and type
1 === '1'
// returns false
operator: != description: not equal to
12 != 8
// returns true
operator: < description: less than
6 < 7
// returns true
operator: > description: greater than
7 > 6
// returns true
operator: && description: logical and
(7 > 6) && (12 != 8)
// returns true
(7 > 6) && (12 == 8)
// returns false
operator: || description: logical or
const y = 5
(7 > 6) || (y > 7)
// returns true
(y < 4) || (2 == 2)
// returns true
Conditionals
Statements in code that execute and find out the truthiness value and can be identified by the following:
if statement
if(statement == true) {
console.log("execute this code when true")
}
else statement
if(statement == true) {
console.log("execute this code true")
} else {
console.log("execute this code when false")
}
else if statement
const color = "orange"
if(color === "blue") {
console.log("execute this code when true")
} else if(color === "yellow") {
console.log("execute this code when true")
} else {
console.log("execute this code when false")
}
// returns "execute this code when false"
Loops
A loop is a way to execute a block of code several times.
The most common loop is the for loop.
for loop
const fruits = ["apples", "peaches", "plums"]
for(let i = 0; i < fruits.length; i++){
console.log("I love " + fruits[i])
}
// returns
I love apples
I love peaches
I love plums
Control flow in action
// Now let's put this all together
const grades = [75, 44, 92, 98]
for (let i = 0; i < grades.length; i++){
if(grades[i] > 70){
console.log("congrats, you passed!")
} else {
console.log("sorry, you failed!")
}
}
// returns
congrats, you passed!
sorry, you failed!
congrats, you passed!
congrats, you passed!
Learn More
Let's chat about control flow
We learned about flow control in javascript by using conditionals, operators and loops. If you enjoyed this post feel free to leave a comment about your experience working with control flow in your applications.
Happy Coding,
Terry Threatt
Top comments (0)