20. Control structures in Javascript: if, for, while
Page 70 | Listen in audio
Complete HTML, CSS and Javascript course to become a Front End Developer
Chapter 20: Control Structures in Javascript: if, for, while
Control structures in JavaScript are essential for programming because they allow you to control the flow of execution of your code. In this chapter, we will cover the 'if', 'for' and 'while' structures.
1. The 'if' structure
The 'if' control structure is used to execute a block of code if a specified condition is true. The basic syntax is:
if (condition) {
// code to be executed if the condition is true
}
For example, if we want to check if a variable 'x' is greater than 10, we could write:
if (x > 10) {
console.log("x is greater than 10");
}
2. The 'for' structure
The 'for' control structure is used to repeat a block of code a specific number of times. The basic syntax is:
for (initialization; condition; increment) {
// code to be executed on each repetition
}
For example, if we wanted to print the numbers 1 to 5, we could write:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
3. The 'while' structure
The 'while' control structure is used to repeat a block of code as long as a specified condition is true. The basic syntax is:
while (condition) {
// code to be executed while the condition is true
}
For example, if we wanted to print the numbers 1 to 5, we could write:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
These control structures are the foundation of JavaScript programming and are used in almost all programs. They allow you to control the flow of your code, making certain blocks of code only execute under certain conditions or repeat a specific number of times. Understanding how and when to use these frameworks is essential to becoming an effective JavaScript developer.
In the next chapter, we will explore control structures in more depth and learn about other important structures such as 'switch' and 'do-while'. Read on to learn more about how to become an effective front-end developer with our complete HTML, CSS, and JavaScript course.
Now answer the exercise about the content:
Which of the following statements about control structures in Javascript is correct?
You are right! Congratulations, now go to the next page
You missed! Try again.
Next page of the Free Ebook: