Control Structures
Effective programming hinges on the ability to make decisions and control the flow of a program. Control structures are fundamental tools that allow developers to dictate how their code is executed based on conditions and logic. In this blog, we’ll explore common control structures, starting with conditional statements and loops.
Conditional Statements
Section titled “Conditional Statements”Conditional statements enable decisions in a program by branching into different paths depending on the given logical conditions.
if
, else if
, else
Section titled “if, else if, else”The if
statement checks a condition and executes a block of code if it evaluates to true
. Additional conditions can be added using else if
, and a default fallback can be provided with else
.
const age = 18;if (age < 18) { console.log("You are a minor.");} else if (age === 18) { console.log("You just became an adult!");} else { console.log("You are an adult.");}
switch
statements
Section titled “switch statements”switch
is an alternative to multiple if...else
conditions and checks a value against multiple cases.
const day = "Monday";switch (day) { case "Monday": console.log("Start of the work week!"); break; case "Friday": console.log("End of the work week."); break; default: console.log("It's another day of the week.");}
Loops are an essential part of programming, used to repeatedly execute a block of code while a condition is met or for a specified number of times.
for
Loop
Section titled “for Loop”The for
loop is great for running a block of code a specific number of times.
for (let i = 0; i < 5; i++) { console.log(`Iteration: ${i}`);}
while
Loops
Section titled “while Loops”The while
loop runs while a condition is true
.
let count = 0;while (count < 3) { console.log(`Count: ${count}`); count++;}
do...while
Loops
Section titled “do...while Loops”The do...while
loop guarantees the block of code executes at least once, even if the condition is false
.
do { console.log(`Value: ${x}`); x--;} while (x > 0);
Loop Control: break
and continue
Section titled “Loop Control: break and continue”break
is used to exit a loop prematurely, halting further iterations.
for (let i = 1; i <= 10; i++) { if (i > 5) { break; // Exit the loop when i > 5 } console.log(i);}
continue
Section titled “continue”continue
skips the current iteration and moves on to the next one.
for (let i = 1; i <= 5; i++) { if (i === 3) { continue; // Skip iteration when i equals 3 }
console.log(i);}
Conclusion
Section titled “Conclusion”Control structures are at the core of programming logic. They give us the power to create dynamic and robust programs, decision-making capabilities with conditional statements, and efficiency with loops. By mastering these control structures, you’ll take your programming skills to the next level.