PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • 🧑 People tracker
    • 🚗 Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. JavaScript Basics
  2. JavaScript: Loops
  • JavaScript

  • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

  • React Framework

  • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

  • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

  • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

  • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

  • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

  • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios

    • Lab#RE02-1: Router & Hooks

    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management

    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS

    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front

    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request

    • Lab#RE07-1: traffic lights simulation

  • React JS readings
    • ReactJS Resources

On this page

  • 1 Overview
  • 2 The “while” Loop
    • 2.1 Example
    • 2.2 Condition Evaluation
    • 2.3 Single Statement
  • 3 The “do…while” Loop
    • 3.1 Example
    • 3.2 When to Use
  • 4 The “for” Loop
    • 4.1 Syntax
    • 4.2 Example
    • 4.3 Parts of the for Loop
    • 4.4 Loop Algorithm
    • 4.5 Step-by-Step Execution
    • 4.6 Inline Variable Declaration
    • 4.7 Using Existing Variable
  • 5 Skipping Parts
    • 5.1 Omitting begin
    • 5.2 Omitting step
    • 5.3 Omitting everything
  • 6 Breaking the Loop
    • 6.1 Infinite Loop + break
  • 7 Continue to the Next Iteration
    • 7.1 Example: Output Odd Numbers
    • 7.2 Alternative Without continue
  • 8 Labels for break/continue
    • 8.1 Example
    • 8.2 continue with Labels
  • 9 Loop Comparison
  • 10 Examples
    • 10.1 Example 1: Sum Numbers
    • 10.2 Example 2: Factorial
    • 10.3 Example 3: Countdown
    • 10.4 Example 4: Input Validation
    • 10.5 Example 5: Multiplication Table
    • 10.6 Example 6: Find First Even Number
    • 10.7 Example 7: Skip Multiples of 3
    • 10.8 Example 8: Nested Loops - Pattern
    • 10.9 Example 9: Prime Number Checker
    • 10.10 Example 10: FizzBuzz
  • 11 Summary
  • Edit this page
  • View source
  • Report an issue
  1. JavaScript Basics
  2. JavaScript: Loops

JavaScript: Loops

JavaScript Loops

javascript
loops
iteration
JavaScript Loops - while, do…while, and for loops
Author

Pedro GeoGIS

Published

Monday, January 13, 2025

Modified

Monday, October 13, 2025

1 Overview

📘 Loops

Loops are used to repeat the same code multiple times. JavaScript provides several loop structures: the while loop for repeating code while a condition is true, the do...while loop for executing code at least once before checking the condition, and the for loop for iterating a specific number of times. Loops can be controlled with break (exit loop) and continue (skip to next iteration) statements.


2 The “while” Loop

The while loop has the following syntax:

while (condition) {
  // code
  // so-called "loop body"
}

While the condition is truthy, the code from the loop body is executed.


2.1 Example

let i = 0;
while (i < 3) {  // shows 0, then 1, then 2
  alert(i);
  i++;
}

A single execution of the loop body is called an iteration. The loop above makes three iterations.


Warning

Infinite Loops

If i++ was missing from the example above, the loop would repeat forever. Always ensure your loop has a way to terminate!

let i = 0;
while (i < 3) {
  alert(i);
  // Missing i++, infinite loop!
}

2.2 Condition Evaluation

Any expression or variable can be a loop condition, not just comparisons. The condition is evaluated and converted to a boolean by while.

A shorter way to write while (i != 0) is while (i):

let i = 3;
while (i) {  // when i becomes 0, the condition becomes falsy
  alert(i);
  i--;
}

2.3 Single Statement

If the loop body has a single statement, we can omit the curly braces (though not recommended):

let i = 3;
while (i) alert(i--);

3 The “do…while” Loop

The condition check can be moved below the loop body using the do...while syntax:

do {
  // loop body
} while (condition);

The loop will first execute the body, then check the condition, and while it’s truthy, execute it again and again.


3.1 Example

let i = 0;
do {
  alert(i);
  i++;
} while (i < 3);

3.2 When to Use

This form of syntax should only be used when you want the body of the loop to execute at least once regardless of the condition being truthy.

let num;
do {
  num = prompt("Enter a number greater than 100?", 0);
} while (num <= 100 && num);

Usually, the other form is preferred: while(...) {...}.


4 The “for” Loop

The for loop is more complex, but it’s also the most commonly used loop.

4.1 Syntax

for (begin; condition; step) {
  // ... loop body ...
}

4.2 Example

for (let i = 0; i < 3; i++) {  // shows 0, then 1, then 2
  alert(i);
}

4.3 Parts of the for Loop

Part Description Example
begin Executes once upon entering the loop let i = 0
condition Checked before every loop iteration i < 3
body Runs again and again while condition is truthy alert(i)
step Executes after the body on each iteration i++

4.4 Loop Algorithm

Run begin
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ (if condition → run body and run step)
→ ...

That is, begin executes once, and then it iterates: after each condition test, body and step are executed.


4.5 Step-by-Step Execution

// for (let i = 0; i < 3; i++) alert(i)

// run begin
let i = 0

// if condition → run body and run step
if (i < 3) { alert(i); i++ }

// if condition → run body and run step
if (i < 3) { alert(i); i++ }

// if condition → run body and run step
if (i < 3) { alert(i); i++ }

// ...finish, because now i == 3

4.6 Inline Variable Declaration

The “counter” variable i is declared right in the loop. This is called an “inline” variable declaration. Such variables are visible only inside the loop.

for (let i = 0; i < 3; i++) {
  alert(i);  // 0, 1, 2
}
alert(i);  // error, no such variable

4.7 Using Existing Variable

Instead of defining a variable, we could use an existing one:

let i = 0;

for (i = 0; i < 3; i++) {  // use an existing variable
  alert(i);  // 0, 1, 2
}

alert(i);  // 3, visible, because declared outside of the loop

5 Skipping Parts

Any part of for can be skipped.

5.1 Omitting begin

let i = 0;  // we have i already declared and assigned

for (; i < 3; i++) {  // no need for "begin"
  alert(i);  // 0, 1, 2
}

5.2 Omitting step

let i = 0;

for (; i < 3;) {
  alert(i++);
}

This makes the loop identical to while (i < 3).


5.3 Omitting everything

for (;;) {
  // repeats without limits
}

This creates an infinite loop. The two for semicolons ; must be present, otherwise there would be a syntax error.


6 Breaking the Loop

Normally, a loop exits when its condition becomes falsy. But we can force the exit at any time using the special break directive.

let sum = 0;

while (true) {
  let value = +prompt("Enter a number", '');
  
  if (!value) break;  // (*)
  
  sum += value;
}

alert('Sum: ' + sum);

The break directive is activated at line (*) if the user enters an empty line or cancels the input.


6.1 Infinite Loop + break

The combination “infinite loop + break as needed” is great for situations when a loop’s condition must be checked not in the beginning or end of the loop, but in the middle or even in several places of its body.

while (true) {
  // do something
  if (condition) break;
  // do something else
}

7 Continue to the Next Iteration

The continue directive is a “lighter version” of break. It doesn’t stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).


7.1 Example: Output Odd Numbers

for (let i = 0; i < 10; i++) {
  // if true, skip the remaining part of the body
  if (i % 2 == 0) continue;
  
  alert(i);  // 1, then 3, 5, 7, 9
}

For even values of i, the continue directive stops executing the body and passes control to the next iteration of for.


7.2 Alternative Without continue

for (let i = 0; i < 10; i++) {
  if (i % 2) {
    alert(i);
  }
}

From a technical point of view, this is identical to the example above. But using continue helps avoid extra nesting.


Important

No break/continue with ternary operator

Syntax constructs that are not expressions cannot be used with the ternary operator ?. In particular, directives such as break/continue aren’t allowed there.

// This doesn't work:
(i > 5) ? alert(i) : continue;  // continue isn't allowed here

Use if instead.


8 Labels for break/continue

Sometimes we need to break out from multiple nested loops at once.

A label is an identifier with a colon before a loop:

labelName: for (...) {
  ...
}

8.1 Example

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    let input = prompt(`Value at coords (${i},${j})`, '');
    
    // if an empty string or canceled, then break out of both loops
    if (!input) break outer;  // (*)
  }
}

alert('Done!');

The break outer looks upwards for the label named outer and breaks out of that loop.


8.2 continue with Labels

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j == 1) continue outer;
    alert(`i=${i}, j=${j}`);
  }
}

Note

Labels don’t allow “jumping” anywhere

Labels do not allow us to jump into an arbitrary place in the code. A break directive must be inside a code block. Technically, any labeled code block will do:

label: {
  // ...
  break label;  // works
  // ...
}

9 Loop Comparison

Loop Type When to Use
while When you don’t know how many iterations you need
do…while When you need at least one iteration
for When you know how many iterations you need

10 Examples

10.1 Example 1: Sum Numbers

let sum = 0;
let n = 10;

for (let i = 1; i <= n; i++) {
  sum += i;
}

console.log(`Sum of numbers from 1 to ${n} is ${sum}`);
// Output: Sum of numbers from 1 to 10 is 55

10.2 Example 2: Factorial

let n = 5;
let factorial = 1;

for (let i = 1; i <= n; i++) {
  factorial *= i;
}

console.log(`${n}! = ${factorial}`);
// Output: 5! = 120

10.3 Example 3: Countdown

let count = 5;

while (count > 0) {
  console.log(count);
  count--;
}
console.log("Blast off!");

// Output: 5, 4, 3, 2, 1, Blast off!

10.4 Example 4: Input Validation

let password;

do {
  password = prompt('Enter password (min 6 characters):', '');
} while (password.length < 6);

alert('Password accepted!');

10.5 Example 5: Multiplication Table

let num = 7;

console.log(`Multiplication table for ${num}:`);
for (let i = 1; i <= 10; i++) {
  console.log(`${num} x ${i} = ${num * i}`);
}

10.6 Example 6: Find First Even Number

let numbers = [1, 3, 5, 8, 9, 10, 11];
let firstEven;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    firstEven = numbers[i];
    break;  // Exit loop once found
  }
}

console.log(`First even number: ${firstEven}`);
// Output: First even number: 8

10.7 Example 7: Skip Multiples of 3

for (let i = 1; i <= 10; i++) {
  if (i % 3 === 0) continue;  // Skip multiples of 3
  console.log(i);
}
// Output: 1, 2, 4, 5, 7, 8, 10

10.8 Example 8: Nested Loops - Pattern

let rows = 5;

for (let i = 1; i <= rows; i++) {
  let pattern = '';
  for (let j = 1; j <= i; j++) {
    pattern += '* ';
  }
  console.log(pattern);
}

// Output:
// * 
// * * 
// * * * 
// * * * * 
// * * * * *

10.9 Example 9: Prime Number Checker

let num = 17;
let isPrime = true;

if (num <= 1) {
  isPrime = false;
} else {
  for (let i = 2; i < num; i++) {
    if (num % i === 0) {
      isPrime = false;
      break;
    }
  }
}

console.log(`${num} is ${isPrime ? 'prime' : 'not prime'}`);
// Output: 17 is prime

10.10 Example 10: FizzBuzz

for (let i = 1; i <= 20; i++) {
  if (i % 15 === 0) {
    console.log('FizzBuzz');
  } else if (i % 3 === 0) {
    console.log('Fizz');
  } else if (i % 5 === 0) {
    console.log('Buzz');
  } else {
    console.log(i);
  }
}

11 Summary

  • while – The condition is checked before each iteration
  • do…while – The condition is checked after each iteration (executes at least once)
  • for – The condition is checked before each iteration, with additional settings
  • Use break to exit a loop immediately
  • Use continue to skip the current iteration and move to the next one
  • Labels allow breaking out of nested loops
  • Infinite loops can be created with while (true) or for (;;)
  • Always ensure your loops have a termination condition to avoid infinite loops
  • Choose the appropriate loop type based on your needs
Back to top
JavaScript: Conditionals
JavaScript: Functions

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue