Native JavaScript - Conditional Statements and Loops
If and Else in JavaScript
If and else statements in JavaScript are fundamental control structures used to execute different blocks of code based on whether a condition evaluates to true or false.
The if Statement
The
if
statement checks a condition (an expression that returns true or false).If the condition is true, the code inside the
if
block runs.If the condition is false, the code inside the
if
block is skipped.
Syntax:
Example:
The if...else Statement
The
else
statement can be paired withif
to specify code that runs if the condition is false.
Syntax:
Example:
The else if Statement
Use
else if
to test multiple conditions in sequence.JavaScript evaluates each condition in order; the first true condition's block runs, and the rest are skipped.
Syntax:
Example:
Summary Table
if
Executes block if condition is true
if (x > 5)
else
Executes block if previous if
/else if
is false
else { ... }
else if
Tests a new condition if previous is false
else if (x === 0)
In summary:
Use
if
to check a condition.Use
else
to handle the opposite case.Use
else if
to check additional conditions in sequence. These statements are essential for decision-making in JavaScript programs
Switch Case in JavaScript
The switch statement in JavaScript is a control structure used to execute different blocks of code based on the value of an expression. It is often used as a cleaner alternative to multiple if...else if...else
statements when you need to compare a single value against several possible matches
Syntax
The
expression
is evaluated once.The result is compared using strict equality (
===
) to eachcase
value in order.If a match is found, the corresponding block runs.
The
break
statement exits the switch block; otherwise, execution "falls through" to the next case.If no case matches, the
default
block (if present) runs
Example
This code assigns the current weekday name to dayName
Key Points
Strict Comparison: Case values are compared with the expression using
===
. Type must match for a case to be selectedBreak Statement: Prevents code from running into the next case. If omitted, execution continues ("falls through") to the next case
Default Case: Runs if no case matches. It's optional and can appear anywhere in the switch block, but usually comes last
Grouped Cases: Multiple cases can share the same code block by omitting
break
between them:This executes the same code for both case 1 and case 2
When to Use switch
When you need to compare a single variable or expression to several possible values.
When you want cleaner, more readable code than multiple
if...else if
statements
In summary:
The switch
statement is a powerful tool for multi-way branching based on the value of a single expression, offering better readability and maintainability for such scenarios in JavaScript
For Loop in JavaScript
The for loop in JavaScript is a fundamental control structure used to repeat a block of code a specific number of times. It's commonly used for tasks like iterating over arrays, counting, or performing repetitive actions.
Syntax
initialExpression: Initializes a counter variable (runs once before the loop starts).
condition: The loop continues as long as this evaluates to
true
(checked before each iteration).
Basic Example
This prints "Hello, world!" three times because the loop runs while i
is less than 3
How It Works
Initialization: Set up a variable (e.g.,
let i = 0
).Condition Check: If the condition (e.g.,
i < 3
) is true, execute the loop body.Execution: Run the code inside the loop.
Update: Increase (or otherwise update) the variable (e.g.,
i++
).Repeat: Go back to step 2. Stop when the condition is false
Iterating Over Arrays
For loops are often used to process each element of an array:
This loop prints each fruit in the array
Omitting Expressions
All three expressions are optional:
You can omit the initializer if the variable is already declared.
You can omit the update if you update the variable inside the loop.
Omitting the condition creates an infinite loop (not recommended)
Example without initializer:
Looping in Reverse
You can count downwards by adjusting the initialization, condition, and update:
Summary Table
Initialization
Set starting value
let i = 0
Condition
Loop continues while true
i < 5
Update
Change variable after each loop
i++
While Loop in JavaScript
A while loop in JavaScript repeatedly executes a block of code as long as a specified condition evaluates to true
. It is especially useful when you do not know beforehand how many times you need to repeat an action—the loop continues until the condition becomes false
Syntax
The
condition
is evaluated before each iteration.If the condition is
true
, the code block runs.After the code block executes, the condition is checked again.
The loop ends when the condition is
false
Example
In this example, the loop prints numbers from 0 to 4. The variable i
is incremented on each iteration, and the loop stops when i
reaches 5
Key Points
Pre-check Loop: The condition is checked before the code block runs. If the condition is
false
initially, the loop body may not execute at allInfinite Loop Risk: If you forget to update the variable in the condition (e.g.,
i++
), the loop may never end, causing your program to hangUse Cases: While loops are ideal when the number of iterations is not known in advance, such as waiting for a user action or an external event
do...while Loop
A related construct is the do...while loop, which always executes the code block at least once before checking the condition:
Summary Table
while
Before loop body
0
Unknown number of repetitions
do...while
After loop body
1
At least one execution needed
In summary:
The while
loop in JavaScript is a control structure that repeats code as long as a condition is true, making it well-suited for tasks where the number of iterations is not predetermined
Last updated