Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

JS Tutorial

JS HOME JS Introduction JS Where To JS Output JS Statements JS Syntax JS Comments JS Variables JS Let JS Const JS Operators JS Arithmetic JS Assignment JS Functions JS Objects JS Events JS Strings JS String Templates JS Numbers JS Arrays JS Dates JS Math JS Random JS Booleans JS Comparisons JS If Else JS Switch JS Loop For JS Loop While JS Break JS Errors JS Modules JS News 2025-2015

JS Data Types

JS Data Types JS typeof JS toString() JS Type Conversion

JS Strings

JS String Methods JS String Search JS String Reference

JS Numbers

JS Number Methods JS Number Properties JS Number Reference JS Math Reference JS BigInt JS Bitwise JS Operator Reference JS Operator Precedence

JS Dates

JS Date Formats JS Date Get JS Date Set JS Date Reference

JS Statements

JS Statements Reference JS Statements Reserved

JS Arrays

JS Array Methods JS Array Search JS Array Sort JS Array Iterations JS Array Reference JS Array Const

JS Functions

Function Definitions Function Arrows Function Parameters Function Invocation Function this Function Call Function Apply Function Bind Function Closures

JS Objects

Object Definitions Object Properties Object Methods Object Display Object Constructors Object this Object Destructuring Object Prototypes Object Iterations Object Management Object Get / Set Object Protection Object Reference

JS Classes

JS Classes JS Class Inheritance JS Class Static

JS Sets & Maps

JS Sets JS Set Methods JS Set Logic JS Set Reference JS Maps JS Map Methods JS Map Reference

JS Typed Arrays

JS Typed Arrays JS Typed Methods JS Typed Reference

Iterations

JS Loop For In JS Loop For Of JS Iterables JS Iterators

JS RegExp

JS RegExp JS RegExp Flags JS RegExp Classes JS RegExp Metachars JS RegExp Assertions JS RegExp Quantifiers JS RegExp Patterns JS RegExp Objects JS RegExp Methods

JS Async

JS Callbacks JS Asynchronous JS Promises JS Async/Await

JS Versions

JS Versions JS 2009 (ES5) JS 2015 (ES6) JS 2016 JS 2017 JS 2018 JS 2019 JS 2020 JS 2021 JS 2022 JS 2023 JS 2024 JS 2025 JS IE / Edge JS History

JS Programming

JS Strict Mode JS Scope JS Hoisting JS Debugging JS Style Guide JS Best Practices JS Mistakes JS Performance

JS HTML DOM

DOM Intro DOM Methods DOM Document DOM Elements DOM HTML DOM Forms DOM CSS DOM Animations DOM Events DOM Event Listener DOM Navigation DOM Nodes DOM Collections DOM Node Lists

JS Browser BOM

JS Window JS Screen JS Location JS History JS Navigator JS Popup Alert JS Timing JS Cookies

JS Web APIs

Web API Intro Web Validation API Web History API Web Storage API Web Worker API Web Fetch API Web Geolocation API

JS AJAX

AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX PHP AJAX ASP AJAX Database AJAX Applications AJAX Examples

JS JSON

JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Parse JSON Stringify JSON Objects JSON Arrays JSON Server JSON PHP JSON HTML JSON JSONP

JS vs jQuery

jQuery Selectors jQuery HTML jQuery CSS jQuery DOM

JS Graphics

JS Graphics JS Canvas JS Plotly JS Chart.js JS Google Chart JS D3.js

JS Examples

JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor JS Exercises JS Quiz JS Website JS Syllabus JS Study Plan JS Interview Prep JS Bootcamp JS Certificate

JS References

JavaScript Objects HTML DOM Objects


JavaScript For Loop


Loops can execute a block of code a number of times.


JavaScript Loops

Loops are handy, if you want to run the same code over and over again, each time with a different value.

Often this is the case when working with arrays:

Instead of writing:

text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";

You can write:

for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}
Try it Yourself »

Different Kinds of Loops

JavaScript supports different kinds of loops:

  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • for/of - loops through the values of any iterable
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

The For Loop

The for statement creates a loop with 3 optional expressions:

for (expression 1; expression 2; expression 3) {
  // code block to be executed
}

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed.

Example

for (let i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}
Try it Yourself »

From the example above, you can read:

Expression 1 sets a variable before the loop starts (let i = 0).

Expression 2 defines the condition for the loop to run (i must be less than 5).

Expression 3 increases a value (i++) each time the code block in the loop has been executed.



How to use Expression 1

Expression 1 is used to initialize the variable(s) used in the loop (let i = 0).

But, expression 1 is optional.

You can omit expression 1 when your values are set before the loop starts:

Example

let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i++) {
  text += cars[i] + "<br>";
}
Try it Yourself »

You can intiate many values in expression 1 (separated by comma):

Example

for (i = 0, len = cars.length, text = ""; i < len; i++) {
  text += cars[i] + "<br>";
}
Try it Yourself »

How to use Expression 2

Expression 2 is used to evaluate the condition of the initial variable (i < len).

But, expression 2 is also optional.

If expression 2 returns true, the loop will start over again. If it returns false, the loop will end.

Note

If you omit expression 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.


How to use Expression 3

Expression 3 increments the value of the initial variable (i++).

But, expression 3 is also optional.

Expression 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.

Expression 3 can also be omitted (like when you increment your values inside the loop):

Example

let i = 0;
let len = cars.length;
let text = "";
for (; i < len; ) {
  text += cars[i] + "<br>";
  i++;
}
Try it Yourself »

Loop Scope

Using var in a loop:

Example

var i = 5;

for (var i = 0; i < 10; i++) {
  // some code
}

// Here i is 10
Try it Yourself »

Using let in a loop:

Example

let i = 5;

for (let i = 0; i < 10; i++) {
  // some code
}

// Here i is 5
Try it Yourself »

In the first example, using var, the variable declared in the loop redeclares the variable outside the loop.

In the second example, using let, the variable declared in the loop does not redeclare the variable outside the loop.

When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.