Lambda School Pre-course 11: Learn to write a basic for loop

There are nine units in Lambda School’s Full Stack Web Development Pre-course. I’m going to summarize what the pre-course covers for each of them. This material is basically ground-floor information that students need to know before they start the full course.

precourse11

Loops

A loop is code that repeats a set of actions until a specific condition fails – essentially while a condition is either true or not true, depending on the purpose of the loop. Each time a loop repeats, its called an iteration.

As per the Lambda School text:

Most software runs on loops, evaluating expressions over and over again until it either returns what we are looking for, or stops after a certain time. JavaScript has two looping expressions built into it and today we will look at the first one, the “for” loop.

for Loops

The syntax for a for loop is more complex than that of an if statement. Its set up with the for keyword, parenthesis and open and close braces ( for (loop condition code) {action code} ). Inside of the parenthesis are three items, each separated by a semicolon:

  1. a declared variable to loop over
  2. a conditional expression that stops the loop upon becoming false
  3. a variable incrementer
for (let i = 0 ; i < 10 ; i++ ) {console.log(i);}
// | declare a var | conditional expression | increment var|

In the above example, the counter variable is initially set to 0. The loop will run and increment the counter by one as it completes each iteration. It will also evaluate the conditional expression during each iteration. If the expression remains true, it will run again, but if it becomes false, the loop will stop running.

The ++ operator

The ++ operator is JavaScript shorthand to add 1 to the current value of the given variable. I came across its counterpart online – the operator, which subtracts 1 from the value of the given variable, so one is an incrementer and the other is a decrementer.

Infinite Loops

An infinite loop is a loop that never stops, because because it has no terminating clause or has one that’s impossible to meet. For example:

for (let i = 0; i >= 0; i++) {console.log(i);}

Because the above conditional expression will ALWAYS be true (it will never be less than 0) this loop will run forever. This can break the program and even crash the web browser or computer.

Leave a comment