DEV Community

Charity Parks
Charity Parks

Posted on

Javascript 'For Loops'

What is the purpose of a 'for loop' in JavaScript? Its purpose is that it executes a block (of code) as long as its condition is met/returns 'true'. Conversely, if the the block is executed and the condition isn't met/returns 'false', the loop will stop.

'For loops' have three arguments:

Initialization - this declares a counter variable

Condition - a condition is evaluated before each loop begins to see if it returns 'true'

Increment - this updates the loop counter each time the loop executes.

These 'for loops' are great for repetitive tasks. With each iteration of the loop, it runs the same block of code with a different value (the incremental aspect). Here is an example of a 'for loop':

for (let number = 0; number <= 12; number = number + 2) {
console.log(number);
}
// 0
// 2
// 4
// 6
// 8
// 10
// 12
(and it stops here)

Happy Coding!

Top comments (0)