Search⌘ K

Introduction to Loops

Explore how JavaScript loops work to repeat instructions based on conditions. Understand the purpose of loops by examining the Fibonacci sequence example, and learn how loops help write concise, efficient code for repetitive tasks.

We'll cover the following...

Background

There are certain parts of a program where you want to repeat an instruction or set of instructions. Take for example the following piece of code.

Node.js
var first = 0; // initialise first number
var second = 1; // initialise second number
var temp = NaN; // a temporary variable for swapping
// calculate the third fibinacci number
temp = second;
second = first + second;
first = temp;
// calculate the fourth fibinacci number
temp = second;
second = first + second;
first = temp;
// calculate the fifth fibinacci number
temp = second;
second = first + second;
first = temp;
console.log(`first: ${first}, second:${second}`);

The above code calculates the fifth number in a Fibonacci sequence. A Fibonacci sequence is where each term ...