MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • JavaScript while Loop
  • Introduction
  • JavaScript while Loop
  • Introduction
  • What is while meant for?
  • Syntax of while
  • Examples
  1. 1st month
  2. Week 4
  3. Javascript
  4. Loops and Iterations

while statement

Previousdo…while statementNextWeekly Review

Last updated 1 year ago

> > > Loops - while Loop

JavaScript while Loop

What will you learn in this page?

  1. What is the while loop meant for

  2. Syntax of while

  3. Basic while examples

  4. The do...while loop

  5. Nested loops

Introduction

As we learnt in the previous chapter on the , there are essentially two main categories of loops in JavaScript — for and while. We've already covered for quite extensively, and likewise what's left now is while.

In this chapter, we aim to unravel the purpose behind while in addition to considering an array of various examples of its usage. Without any single doubt, while forms a crucial part of modern-day programming. Many many algorithms are powered by the powerful nature of while.

So what is while? Let's see it...

> > > Loops - while Loop

JavaScript while Loop

What will you learn in this page?

  1. What is the while loop meant for

  2. Syntax of while

  3. Basic while examples

  4. The do...while loop

  5. Nested loops

Introduction

In this chapter, we aim to unravel the purpose behind while in addition to considering an array of various examples of its usage. Without any single doubt, while forms a crucial part of modern-day programming. Many many algorithms are powered by the powerful nature of while.

So what is while? Let's see it...

What is while meant for?

By design:

The while loop is meant to repeatedly execute a piece of code an unknown number of times.

For instance, if we want to print 'Hello' until the user enters -1 in an input prompt, what we need is the while loop.

Similarly, if we want to iterate over a queue, removing items one-by-one, until there is no item left, this could also be done using a while loop.

Technically speaking, anything that can be done, or is done, using while can also be done using for, and vice versa. It's just that the syntax of while sometimes suits the situation better and obviously asks for less setup than a for loop.

Let's now see the syntax of while.

Syntax of while

The while loop begins with the while keyword, followed by a pair of parentheses (()) encapsulating the condition of iteration, followed by the loop's body.

Here's a programmatic view of this syntax:

while (condition) statement;

The loop continues iterating as long as the given condition remains true. The moment it becomes false, the loop ends.

If you recall, this is identical to how the condition in a for loop works — that is, if it's true, the next iteration happens, or else the loop ends.

With the syntax also done, it's finally time to consider some quick examples.

Examples

Suppose we want to compute the sum a couple of positive numbers entered by the user.

The way the entry happens is via an input prompt for the first number, followed by another input prompt for the second number, and so on, until the value entered is -1. -1 signals the end of the whole stream of numbers to add.

Such a special value is often referred to as a sentinel. A loop that iterates up until the point a sentinel is seen is, likewise, referred to as a sentinel-controlled loop.

Anyways, this task can very easily be accomplished with the help of while as shown below:

var sum = 0;
var input = prompt('Enter a number, -1 to exit.');

while (input !== '-1') {
   sum += Number(input);
   input = prompt('Enter a number, -1 to exit.');
}

alert(`The sum is ${sum}.`);

If we were to accomplish the same thing using for, we'd go like:

var sum = 0;
var input = prompt('Enter a number, -1 to exit.');

for (; input !== '-1'; ) {
   sum += Number(input);
   input = prompt('Enter a number, -1 to exit.');
}

alert(`The sum is ${sum}.`);

See how the syntax of for is a little bit less intuitive and a little more to type. In this case, while is definitely the better choice.

As another example, suppose we want to remove elements from the end of an array, using the pop() method, until it becomes empty. This also can be done nicely using a while loop.

Consider the following code:

var arr = [1, 3, 5];

while (arr.length !== 0) {
   console.log(arr.pop());
}

5 3 1

The condition arr.length !== 0 checks if the array has anything remaining in it. If there is something remaining, the condition evaluates to true, and hence the loop's body executes, thereby removing the last element from the array (via the arr.pop() call).

Note that arr.pop() effectively reduces the length of arr as the loop progresses and thus takes it closer and closer to the success of the condition arr.length !== 0. Without arr.pop(), we'd get an infinite loop.

Recall that an infinite loop is one that runs forever and causes the current program to simply crash!

Although the code above works perfectly, you'll often see one common convention used out there to check whether an array has elements remaining within it.

That is, for a given array arr, instead of using arr.length !== 0 to check whether there are any remaining elements in arr, the expression arr.length is used.

When it coerces to true, it simply means that the array's length is not 0 and hence there is still something remaining in it. This is effectively identical to arr.length !== 0.

Likewise, the code above can be rewritten as follows:

var arr = [1, 3, 5];

while (arr.length) {
   console.log(arr.pop());
}

5 3 1

The while loop here can be read as: "while the array has some length, keep removing its last element."

Once again, remember that if arr.length returns a positive number (which means that arr has some elements in it), it would coerce to the Boolean value true, and thus get the loop to be executed.

As we learnt in the previous chapter on the , there are essentially two main categories of loops in JavaScript — for and while. We've already covered for quite extensively, and likewise what's left now is while.

1️⃣
Home
Courses
JavaScript
LoopsSelection Sort Exercise
LoopsCollatz Conjecture Exercise
for loop
Home
Courses
JavaScript
LoopsSelection Sort Exercise
LoopsCollatz Conjecture Exercise
for loop
Live Example ↗