javascriptlesson5
javascriptlesson5
o Control flow refers to the order in which the computer executes statements in a script.
JavaScript normally runs code line by line, but control flow allows the code to make
decisions and repeat actions.
if Statement:
Example:
You can use else to define a block of code that will run if the condition is false, and else if to
check multiple conditions.
Example:
o The switch statement is another way to execute different blocks of code based on
different conditions. It’s often used when there are multiple possible outcomes for a
single expression.
Example:
o The switch statement is generally used when you have many conditions based on the
same value. It can be cleaner and more readable than using multiple if-else statements.
Introduction to Loops:
o Loops allow you to repeat a block of code multiple times until a specified condition is
met. JavaScript supports several types of loops, including for, while, and do...while.
for Loop:
o The for loop is the most common loop used to iterate over arrays and other sequences.
Example:
Explanation:
while Loop:
Example:
do...while Loop:
o The do...while loop is similar to the while loop, but it guarantees the loop will run at
least once, because the condition is checked after the code block is executed.
Example:
forEach() Loop:
The forEach() loop is specifically designed to loop through arrays. It takes a callback function that
will be executed for each element of the array.
Example:
o Errors in your code can stop your program from working correctly. JavaScript provides
mechanisms to catch and handle errors, so your program doesn't crash unexpectedly.
try...catch Block:
o The try...catch statement allows you to run code that may throw an error and handle
that error gracefully.
Example:
throw Statement:
You can also throw your own errors using the throw statement.
Example: