#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
JavaScript Fundamentals

Loops

A loop runs the same block of code repeatedly, either a fixed number of times, once for each item in a collection, or until a condition stops being true. Loops let you print a times table, total the prices in a cart, or process every row of data without writing the same line over and over. JavaScript has several loop forms, and each one fits a particular situation.

The counting loop: for

The classic for loop has three parts in its parentheses: a starting statement, a condition checked before every pass, and an update that runs after every pass.

// Counting
for (let i = 1; i <= 5; i++) {
  console.log(`7 x ${i} = ${7 * i}`);
}

// Looping over array values
const prices = [120, 80, 300];
let total = 0;
for (const price of prices) {
  total += price;
}
console.log(total);            // 500

// Looping over object keys
const stock = { pens: 40, books: 12 };
for (const item in stock) {
  console.log(item, stock[item]);
}

// Repeat until a condition changes
let attempts = 0;
while (attempts < 3) {
  attempts++;
}

// Runs at least once
let input;
do {
  input = getNextValue();
} while (input !== 'quit');

Picking the right loop

LoopBest for
forCounting, or when you need the index and control over steps
for...ofValues of arrays, strings, Sets, Maps and NodeLists
for...inKeys of a plain object
whileRepeating until something changes, when the count is unknown
do...whileLike while, but the body must run at least once

Arrays also have methods such as forEach, map and filter that loop for you. They are often clearer for transforming data, but they cannot be stopped early with break, so a for...of loop is better when you want to stop at the first match.

Controlling the flow: break and continue

break exits the loop immediately. Use it when you have found what you were looking for. continue skips the rest of the current pass and moves on to the next one, which is handy for ignoring invalid items. For example, inside a loop over orders, if (order.cancelled) continue; skips cancelled orders without nesting the rest of the code inside an if.

Bugs that show up in loops

Infinite loops. If the condition never becomes false, the loop runs forever and the browser tab freezes. This usually happens when you forget to update the counter in a while loop, or update the wrong variable. Check that something inside the loop moves it toward the end.

Off-by-one errors. Arrays start at index 0 and end at length - 1. Writing i <= arr.length runs one extra time and reads undefined. Use i < arr.length.

Using for...in on arrays. for...in gives keys as strings ("0", "1"), can include inherited properties, and is not meant for arrays. Use for...of for values, or a counting for loop when you need the index. If you need both, for (const [i, value] of arr.entries()) gives you each.

Changing an array while looping. Removing items from the array you are looping over shifts the remaining items and skips some. Build a new array with filter instead, or loop backwards.

Summary

Use for when counting, for...of for values, for...in for object keys, and while when you do not know how many passes you need. Always make sure the loop has a clear way to finish.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course