View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
  1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
9

JavaScript Loops

Updated on 06/08/2024444 Views

Ever found yourself writing the same block of code over and over, just with slightly different values? If so, I believe that JavaScript loops are your solution. They let us make our code incredibly organized. 

According to me, JavaScript loops are a superpower for any web developer. They let us automate repetitive tasks, work with collections of data, and write code that's both efficient and elegant. 

In this tutorial, we'll unpack the different types of JavaScript loops and see how they can streamline your coding.

What is Looping in Programming?

In programming, looping is a way to repeat a block of code multiple times. It saves us from writing the same instructions over and over, making code more efficient and less prone to errors.

What are JavaScript Loops?

JavaScript loops are control structures that allow us to repeat a block of code multiple times based on certain conditions. They are essential for automating tasks and making our code more efficient.

Types of Loops in Javascript

JavaScript offers several types of loops to handle different repetition scenarios:

  • for loop: The classic choice when you know the number of times you want to repeat the code block.

Example:

Code:

for (let i = 0; i < 10; i++) {

  console.log("Iteration count: " + i);

}

The classic for loop is ideal when you know the exact number of times you want the code to repeat. This loop initializes a counter variable i to 0. It repeats as long as the value of i is less than 10. Inside the loop, it prints the current iteration count. After each iteration, i is incremented by 1.

  • while loop: Keeps executing a code block as long as a specific condition remains true.

Example:

Code:

let userInput = '';

while (userInput !== 'quit') {

  userInput = prompt("Enter a value (type 'quit' to exit):"); 

  console.log("You entered: " + userInput);

}

The while loop continues executing a code block as long as a specified condition evaluates to true. In this example, the loop prompts the user for input until the user types the word 'quit', at which point, the loop terminates.

  • do...while loop: Similar to a 'while' loop, but guarantees the code block runs at least once.

Example:

Code:

let shouldContinue = true;

do {

  let input = prompt("Enter a number (or type 'quit' to exit): ");

  if (input === 'quit') {

    shouldContinue = false;

  } else {

    // Process the number input

    console.log("You entered: ", input);

  }

} while (shouldContinue);

In this example, the JavaScript loops code prompts the user for input and processes it. The loop continues as long as shouldContinue is true. If the user enters 'quit', shouldContinue is set to false, and the loop terminates.

  • for...in loop: Designed to iterate over the properties of an object.

Example:

Code:

const car = {

    brand: "Ford",

    model: "Mustang",

    year: 1969

};

for (const property in car) {

  console.log(`${property}: ${car[property]}`);

}

In this example, the loop accesses each property of the car object using the variable property. It prints the property name and its corresponding value to the console.

  • for...of loop: A versatile loop for iterating over iterable objects (like arrays and strings).

Example:

Code:

const colors = ['red', 'green', 'blue'];

for (const color of colors) {

  console.log(color);

}

The for...of loop lets you iterate directly over elements within arrays or other iterable objects. In this example, the loop assigns each color in the colors array to the variable color during each iteration and prints it to the console.

Here is an example of using the different types of Loops in Javascript together:

Code:

// for loop: Print numbers 1 to 5

for (let i = 1; i <= 5; i++) {

  console.log(i); 

}

// while loop: Print numbers until a user enters 'quit'

let input = '';

while (input !== 'quit') {

  input = prompt("Enter a number (or 'quit' to exit): ");

  if (input !== 'quit') {

    console.log(input); 

  }

}

// for...of loop: Print characters of a string

const word = "hello";

for (const letter of word) {

  console.log(letter); 

}

Why JavaScript Loops?

Here are some reasons why JavaScript loops are important:

  • Automation: JavaScript loops let us tackle repetitive tasks without writing the same code endlessly.
  • Efficiency: JavaScript loops streamline code, making it more concise and easier to maintain.
  • Working with data: JavaScript loops are essential for tasks like processing arrays, manipulating strings, and many more.

JavaScript Loops Examples

Here are some JavaScript loops programs:

1. Nested Loops

Loops can be placed within other loops for complex operations. Here's an example to create a multiplication table:

The outer loop iterates through rows, while the inner loop iterates through columns. For each combination of i and j, the multiplication result is printed.

2. Break and Continue

You can change the flow of loops using break and continue statements.

Code:

// Break example:

for (let i = 1; i <= 10; i++) {

  if (i === 5) {

    break; // Exit the loop completely

  }

  console.log(i);

// Continue example:

for (let i = 1; i <= 10; i++) {

  if (i % 2 === 0) {

    continue; // Skip the current iteration 

  }

  console.log(i);

In the break example, the loop terminates when i reaches 5. In the continue example, the loop skips even numbers.

3. Looping over Objects

While the for...in loop can iterate over object properties, other techniques are often more suitable:

Code:

const person = { name: "Alice", age: 30, hobbies: ['coding', 'reading'] };

// Using Object.keys() and for...of

for (const key of Object.keys(person)) {

  console.log(`${key}: ${person[key]}`);

}

// Using Object.entries() and for...of

for (const [key, value] of Object.entries(person)) {

  console.log(`${key}: ${value}`);

}

Object.keys() creates an array of object property names, letting us loop over them. Meanwhile, Object.entries() provides key-value pairs for more direct access within the loop.

If you wish to learn tools such as JavaScript and web development, you can check out upGrad’s full stack development courses.

JavaScript Loops Exercise

Let us get some JavaScript loops practice with these exercises:

Exercise 1:  Matrix Manipulation

Task: Create a function rotateMatrix(matrix) that takes a 2D array (representing a matrix) as input and returns a new matrix rotated 90 degrees clockwise.

Hints: Nested loops will be crucial here. Consider how the indices of the original matrix map to those of the rotated version.

Example:

const originalMatrix = [

    [1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]

];

const rotatedMatrix = rotateMatrix(originalMatrix); 

// rotatedMatrix should be:

// [

//  [7, 4, 1],

//  [8, 5, 2],

//  [9, 6, 3] 

// ]

Exercise 2:  Finding the Anagrams

Task: Write a function findAnagrams(words) that takes an array of words and returns an array of groups where each group contains words that are anagrams of each other.

Hints: You'll need to manipulate strings to check if they are anagrams. Think sorting characters or creating a character frequency map as potential approaches. Consider nested loops, and maybe dictionaries (objects).

Example:

const words = ["eat", "tea", "silent", "listen", "banana"]; 

const anagramGroups = findAnagrams(words); 

// anagramGroups should be: 

// [ ["eat", "tea"], ["silent", "listen"], ["banana"] ]

Exercise 3:  Custom Iterator

Task: Implement a custom iterator for a tree-like data structure. This involves creating an object with a next() method that will traverse the tree in a specific order (e.g., pre-order, in-order, post-order).

Hints: Understanding recursion may be helpful here.

Exercise 4: The Skyline Problem

Task: You're given an array representing the heights of rectangular buildings on a 2D skyline (where each index is a position, and the value is the building's height). Write a function calculateSkyline(buildings) that returns an array of points representing the key points of the skyline contour.

Hints: Think about how the silhouette changes when you scan from left to right. You might need to maintain a data structure to track the 'active' buildings as you progress.

Example:

const buildings = [2, 5, 3, 1, 6, 2, 4];

const skyline = calculateSkyline(buildings); 

// skyline should be: [(0,2), (2,5), (3,3), (4,6), (6,4), (7,0)] 

Exercise 5: Flatten Nested Data Structures

Task: Write a function deepFlatten(data) that takes an array which may contain nested arrays (to arbitrary levels) and returns a single flattened array.

Hints: Recursion will be your friend! Consider how to handle arrays within arrays.

Example:

const nestedData = [1, [2, 3, [4]], 5];

const flattened = deepFlatten(nestedData); 

// flattened should be: [1, 2, 3, 4, 5]

Exercise 6:  Custom Looping

Task: Instead of using regular loops, implement functions with these behaviors using higher-order functions like map, filter, reduce (or combinations of them):

  • A function that iterates over an array and executes a callback for every second element.
  • A function that sums all the numbers in an array that are divisible by 3.

Exercise 6:  Custom Looping

Task: Instead of using regular loops, implement functions with these behaviors using higher-order functions like map, filter, reduce (or combinations of them):

  • A function that iterates over an array and executes a callback for every second element.
  • A function that sums all the numbers in an array that are divisible by 3.

Exercise 7:  Sparse Matrix Multiplication

Task: Represent sparse matrices (matrices with lots of zeros) efficiently and implement a function multiplySparseMatrices(matrixA, matrixB) to multiply them.

Hints: Instead of storing full 2D arrays, think about using objects or other structures to only keep track of the non-zero elements. Your multiplication algorithm will need to adapt.

Exercise 8: Game Loop

Task: Using JavaScript's timing functions (requestAnimationFrame might come in handy), create a simple game loop that:

  1. Updates game logic (e.g., moves objects based on rules).
  2. Renders the game state to the screen (this could be as simple as updating text, or more complex using libraries like Canvas).

Hints: The game loop should run continuously, aiming for a smooth frame rate.

Exercise 9:  Custom Range Function

Task: Go beyond JavaScript's built-in iterators and create a customRange function that generates number sequences similar to Python's range function. Allow it to take:

  • start
  • end (optional, if omitted, starts from 0 and goes up to start)
  • step (optional, defaults to 1)

Example:

for (const num of customRange(5)) { 

    console.log(num); // 0, 1, 2, 3, 4

}

for (const num of customRange(2, 8, 2)) {

    console.log(num); // 2, 4, 6

}

Wrapping Up

JavaScript loops offer an incredibly powerful and flexible toolkit for controlling the flow of your programs. Whether we need to iterate over arrays and objects, or simply repeat actions a set number of times, I believe that there's a loop to fit the task. 

Understanding how to choose the right loop for different scenarios is a core JavaScript skill.  From basic iterations to complex nested structures, loops allow us to write more concise, efficient, and maintainable code.

If you wish to learn JavaScript and other tools for developing websites and applications, you can enroll in any of upGrad’s software engineering courses that teach JS.

Frequently Asked Questions

What are the loops in JavaScript?

JavaScript has several loop types: for, while, do...while, for...in, and for...of.

What is a while loop JavaScript?

A while loop in JavaScript repeats a code block as long as a specified condition remains true.

What is the syntax of for loop?

The basic for loop syntax is: for (initialization; condition; increment/decrement) { code to execute }

How many loops in Java?

Java has the same loop types as JavaScript: for, while, do...while, and variations of the for loop (for-each).

How many loops in JavaScript?

JavaScript also has five loop types: for, while, do...while, for...in, and for...of.

What is loop example?

A simple loop example: for (let i = 0; i < 10; i++) { console.log(i); } This prints numbers 0 to 9.

What is loop explain?

A loop is a programming construct that repeats a block of code until a specific condition is met.

What is called loop?

Loops such as JavaScript loops are control structures that lets us to repeat a block of code multiple times based on certain conditions

What is loop in coding?

In coding, a loop is a way to automate repetitive tasks and control the flow of execution within a program.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .