JavaScript - Control Structures Flashcards
What are Control Structures?
Control structures are programming tools that manage the flow of code execution. They allow us to make decisions and repeat actions in our programs. Essential for creating dynamic and responsive JavaScript applications. We’ll explore conditional statements, loops, and other control structures.
Why are, If Else and Else statements used?
Used for Making Decisions in Code/Javascript.
Syntax (Code Outline) for If, If Else and Else Statements :
if (condition) {
// code to run if condition is true
} else if (anotherCondition) {
// code to run if anotherCondition is true
} else {
// code to run if no conditions are true
}
Why are Switch Statements used?
Used when you have Multiple Conditions to check against a single value.
Syntax (Code Outline) for Switch Statements :
switch (expression) {
case value1:
// code to run
break;
case value2:
// code to run
break;
Why are While Loops used?
Repeats a block of code while a condition is true. Remember to be careful to avoid infinite loops.
Syntax (Code Outline) for While Loops :
while (condition) {
// code to repeat
}
Example of Code counting down from 10 to 1 using While Loops.
let count = 10;
while (count >= 1) {
document.write(count);
count–;
Why are Do While Loops used?
Similar to while loop, but guarantees the code block runs at least once. Useful when you need to execute code before checking the condition
Syntax (Code Outline) for Do While Loops :
do {
// code to repeat
} while (condition);
Example of Code for Asking for user input until valid using Do While Loops.
let userInput;
do {
userInput = prompt(“Please enter a number between 1 and 10:”);
userInput = Number(userInput);
} while (isNaN(userInput) || userInput < 1 || userInput > 10);
document.write(“Valid input: “ + userInput);
Comparison between Do While and While Loops ?
While Loop : hecks condition first and may not execute if condition is initially false.
Do While Loop : Executes code block first, then checks condition
and always executes at least once. Choose based on whether you need guaranteed execution.