for
LoopsThe for
loop is ubiquitous in the programming world. Almost every programming language has one and many employers will use a for
loop challenge in their hiring process.
i
) that keeps track of which iteration the program is in.for
loop.for
loop syntax
for ([initializer]; [condition]; [increment]) {
// Your code here
}
To Print 1-to-100 with a for Loop.
for (let i = 1; i <= 100; i++) {
console.log(i);
}
for
Loop Flowchartfor
loop processinitializer
expression executes and creates one or more loop counters. The syntax allows an expression of any degree of complexity but is usually i = 0
or i = 1
. i
.for
loop processcondition
expression is evaluated. condition
is true
, the loop statements within the code block execute (Step 3). condition
is false
, the for
loop terminates and the script proceeds to the next line after the loop.for
loop processincrement
expression is executed. This usually increases the counter by 1 (i++
).i
.for
loop are reset on each iteration.for
loop are not available outside the loop.let
when initializing i
. const
won't work if i
is incremented or overwritten.condition
. It's easy to be "one off" when choosing comparison operators such as <
and <=
.break
and continue
break
The break
statement "jumps out" of a loop.
for (let i = 1; i <= 10; i++) {
if (i === 4) {
break;
}
console.log(i);
}
// Output: 1, 2, 3
continue
The continue statement skips one iteration in the loop.
for (let i = 1; i <= 10; i++) {
if (i === 4) {
continue;
}
console.log(i);
}
// Output: 1, 2, 3, 5, 6, 7, 8, 9, 10
for
statementfor
Loopfor
Loop by Mosh Hamedani