The control flow is the order in which the computer executes statements in a script. Code is run in order from the first line in the file to the last line
, unless the computer runs across the structures that change the control flow, such as conditionals and loops.
For example, imagine a script used to validate user data from a webpage form. The script submits validated data, but if the user, say, leaves a required field empty, the script prompts them to fill it in.
To do this, the script uses a conditional structure
or if...else
statement , so that different code executes depending on whether the form is complete or not.
if (isEmpty(field)) {
promptUser();
} else {
submitForm();
}
In simpler terms, control flow defines the path your program takes as it runs, which statements are executed when, and which ones may be skipped or repeated.
Control structures are statements in our code that help us manage control flow. They provide a way to control the order in which instructions are executed based on certain conditions or criteria.
There are three primary types of control structures in JavaScript:
-
Sequential Structure
: Code is executed in the order it appears, from top to bottom, without any branching or looping. -
Selection Structure
: These are conditional statements that allow you to make decisions in your code. In JavaScript, we useif...else
if
, andelse
statements to control which block of code gets executed based on a condition.
if (condition) {
// Code to execute when the condition is true
} else {
// Code to execute when the condition is false
}
Repetition Structure
: Repetition structures, commonly known as loops, allow you to execute a block of code multiple times. JavaScript provides loop constructs likefor
,while
, anddo...while
to control repetitive execution.
In any programming language, the code needs to make decisions and carry out actions accordingly depending on different inputs.
As a human beings or even other animals make decisions all the time that affect their lives, from small to large. Such as:
- Should I eat one cookie or two?
- Should I go to market or not?
- What should I do after 12th?, like that...
Conditional statements allow us to represent such decision making in JavaScript, Such as if...else statements.
The if...else
statement executes a statement if a specified condition is truthy
. If the condition is falsy
, another statement in the optional else
clause will be executed.
Here is the syntax of the if...else
statement.
if (condition) {
// statement1
}
// With an else clause
if (condition) {
// statement1;
} else {
// statement2;
}
Syntax explanation:
-
condition
: An expression that is considered to be either truthy or falsy. -
statement1:
Statement that is executed if condition is truthy. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement{ *** }
to group those statements. To execute no statements, use an empty statement. -
statement2
: Statement that is executed if condition is falsy and the else clause exists. Can be any statement, including block statements and further nested if statements. Multipleif...else
statements can be nested to create anelse if
clause. Note that there is noelseif
(in one word) keyword in JavaScript.
if (condition1) statement1;
else if (condition2) statement2;
else if (condition3) statement3; // … else statementN
The conditional or ternary (Ternary means 3
) operator is the only JavaScript operator that takes three operands:
- A condition followed by a question mark (
?
) - An expression to execute if the condition is truthy followed by a colon (
:
) - The expression to execute if the condition is falsy.
This operator is frequently used as an alternative to an if...else
statement. Here is the syntax of the ternary operator:
condition ? exprIfTrue : exprIfFalse;
Explanation of the above syntax:
condition
: An expression whose value is used as a condition.exprIfTrue
: An expression which is executed if the condition evaluates to a truthy value.exprIfFalse
: An expression which is executed if the condition is falsy.
Besides
false
value, possible falsy expressions are:null
,NaN
,0
, the empty string""
, andundefined
. If condition is any of these, the result of the conditional expression will be the result of executing the expressionexprIfFalse
.
const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"
One common usage is to handle a value that may be null:
const greeting = (person) => {
const name = person ? person.name : "stranger";
return `Howdy, ${name}`;
};
console.log(greeting({ name: "Alice" })); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"
The ternary operator is right-associative
, which means it can be chained
in the following way, similar to an if … else if … else if … else
chain.
condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4;
This is equivalent to the following if...else
chain.
function example() {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}