Learn JavaScript
  • Introduction
  • Basics
    • Comments
    • Variables
    • Types
    • Equality
  • Numbers
    • Math
    • Basic Operators
    • Advanced Operators
  • Strings
    • Creation
    • Replace
    • Length
    • Concatenation
  • Conditional Logic
    • If
    • Else
    • Switch
    • Comparators
    • Concatenate
  • Arrays
    • Unshift
    • Map
    • Spread
    • Shift
    • Pop
    • Join
    • Length
    • Push
    • For Each
    • Sort
    • Indices
  • Loops
    • For
    • While
    • Do...While
  • Functions
    • Higher Order Functions
  • Objects
    • Properties
    • Mutable
    • Reference
    • Prototype
    • Delete
    • Enumeration
    • Global footprint
  • Linked List
    • Add
    • Pop
    • Prepend
    • Shift
  • Browser Object Model (BOM)
    • Window
    • Popup
    • Screen
    • Navigator
    • Cookies
    • History
    • Location
  • Date and Time
  • JSON
  • Error Handling
    • try...catch...finally
  • Events
  • Regular Expression
  • Modules
  • Debugging
  • Classes
    • Static
    • Inheritance
    • Access Modifiers
  • Promise, async/await
    • Async/Await
  • Miscellaneous
    • Hoisting
    • Currying
    • Polyfills and Transpilers
  • Exercises
    • Console
    • Multiplication
    • User Input Variables
    • Constants
    • Concatenation
    • Functions
    • Conditional Statements
    • Objects
    • FizzBuzz Problem
    • Get the Titles!
Powered by GitBook
On this page

Was this helpful?

  1. Loops

For

The easiest form of a loop is the for statement. This one has a syntax that is similar to an if statement, but with more options:

for (condition; end condition; change) {
    // do it, do it now
}

Let's see how to execute the same code ten-times using a for loop:

for (let i = 0; i < 10; i = i + 1) {
  // do this code ten-times
}

Note: i = i + 1 can be written i++.

To loop through the properties of an object or an array for in loop can also be used.

for (key in object) {
  // code block to be executed
}

Examples of for in loop for an object and array is shown below:

const person = {fname:"John", lname:"Doe", age:25};
let info = "";
for (let x in person) {
  info += person[x];
}

// Result: info = "JohnDoe25"

const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
  txt += numbers[x];
}

// Result: txt = '45491625'

The value of iterable objects such as Arrays, Strings, Maps, NodeLists can be looped using for of statement.

let language = "JavaScript";
let text = "";
for (let x of language) {
text += x;
}
PreviousLoopsNextWhile

Last updated 2 years ago

Was this helpful?