Learn JavaScript
Lesson 1 - Introduction To JavaScript
Lesson 2 - Basic JavaScript Syntax
Lesson 4 - Functions
Lesson 5 - Basic Data Structures
Lesson 6 - Basic String Operations
Lesson 7 - Basic Array Operations
Lesson 8 - Exception Handling
Lesson 9 - Packages
Lesson 10 - User Input
Loops are used to execute a block of code repeatedly. There are two types of loops available in JavaScript:
for
loop:
The for
loop allows you to specify the number of times a code block executes. For example:
for (let i = 0; i < 5; i++) { console.log("The value of i is: " + i); }
Here, the for
loop will run until i < 5
. Try to edit the condition.
while
loop:
The while
loop runs a code block continuously until a pre-defined condition is met. Have a look at the following example:
let i = 0; while (i < 5) { console.log("The value of i is: " + i); i++; }
This loop will run until the value of i
is less than 5. Here, i++
increases the value of i
by one every time the loop runs.
Interrupting Loops:
break
: The keyword break
is used to stop the execution of a loop when a certain condition is true
.
for (let i = 0; i < 5; i++) { if (i == 3) break; console.log("The value of i is: " + i); }
The above code will stop immediately when the value of i
equals 3
. Try to change the values and see what happens.
continue
: The keyword continue
is used to skip the execution of a specific code block when a certain condition is true
.
for (let i = 0; i < 5; i++) { if (i == 3) continue; console.log("The value of i is: " + i); }
Here, the program will skip printing when the value of i
equals 3
, which means it will print all the values except 3
.