Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Course Functions in JavaScript
Next article icon

JavaScript Course Loops in JavaScript

Last Updated : 10 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times.

Example: In this example we will print the same things, again and again, to understand the work of Loops.




<script>
    console.log('Hello World');
    console.log('Hello World');
    console.log('Hello World');
    console.log('Hello World');
    console.log('Hello World');
    console.log('Hello World');
    console.log('Hello World');
    console.log('Hello World');
    console.log('Hello World');
    console.log('Hello World');
</script>
 
 

The above code will simply output the sentence ‘Hello World’ to the screen 10 times. Though this method is something I wouldn’t recommend. Though one might argue that you can write console.log ’10’ times, what about printing about the console.log ‘100’ or say ‘10000’ times? The above approach in these cases is just not what anyone would recommend that’s why we make use of loops.
Javascript provides different types of loops.

JavaScript Loops: These are the majorly used loops in javascript.

  • while loop
  • do..while loop
  • for loop

Note: Javascript also includes for..in, for..each, for..of loop though they are beyond the scope of this course.

JavaScript while Loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

  while(condition){   do..this;  }  

The condition/expression we pass inside the parenthesis of the while loop must evaluate to true otherwise the statements we write inside the block of the while loop will not be executed.

Example:




<script>
    // Working while loop example
    let i = 0;
    while( i < 5){
     console.log('Hello World');
       
     // Necessary to increase the iterator value
     i++; 
    } 
</script>
 
 

Output:

  Hello World  Hello World  Hello World  Hello World  Hello World  

The above code simply prints ‘Hello world’ to the screen and all we did is initialized a variable ‘i’ with value ‘0’ assigned to it, then we say that till the value of this variable ‘i’ is less than ’10’ keep doing whatever is written inside the block of the while loop. It is important to increase the value of this variable ‘i’ otherwise it will go into ‘infinite’ loop. Now consider a scenario where we pass something inside the parenthesis which doesn’t evaluate to true, in that case, nothing will be executed which is inside the code block.

Example:




<script>
    // Not working while loop
    let i = 5;
    while( i < 4 ){
     console.log('Hello World');
     i++;
    }
</script>
 
 

Since the condition inside the while loop doesn’t evaluate to true, hence nothing is printed to the screen.

JavaScript do..while Loop: The do-while loop is similar to while loop with the only difference that it checks for the condition after executing the statements. I don’t matter if the condition inside the while parenthesis is true or not the loop will run at least once.

  do  {      statements..  }  while (condition);  

Example:




<script>
    // JavaScript program to illustrate do-while loop 
    let x = 21; 
        
    do 
    { 
        console.log("Value of x: " + x + "<br />"); 
        x++; 
    } while (x < 20); 
        
</script>
 
 

Output:

  Value of x: 21  

JavaScript For Loop: For loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping.

  for (initialization condition; testing condition;  increment/decrement) {    do..this;  }  
  • Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
  • Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
  • Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
  • Increment/ Decrement: It is used for updating the variable for next iteration.
  • Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.

Example:




<script>
    // for loop
    for(let i = 0; i < 5;i++){
     console.log('Value of i is: ' + i );
    }
</script>
 
 

Output:

  Value of i is: 0  Value of i is: 1  Value of i is: 2  Value of i is: 3  Value of i is: 4  


Next Article
JavaScript Course Functions in JavaScript
author
immukul
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Course

Similar Reads

  • Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
    This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you
    4 min read
  • JavaScript Course What is JavaScript ?
    JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScri
    3 min read
  • JavaScript Hello World
    The JavaScript Hello World program is a simple tradition used by programmers to learn the new syntax of a programming language. It involves displaying the text "Hello, World!" on the screen. This basic exercise helps you understand how to output text and run simple scripts in a new programming envir
    2 min read
  • JavaScript Course Understanding Code Structure in JavaScript
    Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. The 'type' attribute was the most important a
    3 min read
  • JavaScript Course Variables in JavaScript
    Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory loca
    4 min read
  • JavaScript Data Types
    In JavaScript, each value has a data type, defining its nature (e.g., Number, String, Boolean) and operations. Data types are categorized into Primitive (e.g., String, Number) and Non-Primitive (e.g., Objects, Arrays). Primitive Data Type1. NumberThe Number data type in JavaScript includes both inte
    6 min read
  • JavaScript Course Operators in JavaScript
    An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used for comparing values, performing arithm
    7 min read
  • JavaScript Course Interaction With User
    Javascript allows us the privilege to which we can interact with the user and respond accordingly. It includes several user-interface functions which help in the interaction. Let's take a look at them one by one. JavaScript Window alert() Method : It simply creates an alert box that may or may not h
    2 min read
  • JavaScript Course Logical Operators in JavaScript
    logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped
    3 min read
  • JavaScript Course Conditional Operator in JavaScript
    JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences