今日已更新 84 条资讯 | 累计 37333 条内容
关于我们

🔄 Loops in JavaScript

ABISHEK M 2026年08月30日 02:20 0 次阅读 来源:Dev.to

Imagine a teacher wants to greet 5 students: Hello Arun Hello Kumar Hello Ravi Hello Priya Hello Divya Without a loop, we need to write the same code multiple times. console . log ( " Hello Arun " ); console . log ( " Hello Kumar " ); console . log ( " Hello Ravi " ); console . log ( " Hello Priya " ); console . log ( " Hello Divya " ); Instead of writing the same type of code again and again, JavaScript provides loops . 🔄 What is a Loop? A loop is used to execute a block of code repeatedly. It helps us avoid writing the same code again and again. A loop continues running based on a condition or a collection of values . In simple words: A loop means repeating a task multiple times using code. For example: For every student: Print the student's name This is the basic idea of a loop. 🤔 Why Do We Use Loops? Loops are useful when the same task needs to be performed multiple times. For example, without a loop: console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); Using a loop: for ( let i = 1 ; i <= 5 ; i ++ ) { console . log ( " Hello " ); } Output: Hello Hello Hello Hello Hello If the task needs to be performed 100 or 1000 times, using a loop is much easier than writing the same code repeatedly. 📍 Where Are Loops Used? Loops can be used in many situations, such as: Displaying a list of products Processing a list of students Reading values from an array Printing numbers Calculating marks Processing multiple records Repeating a task until a condition becomes false For example: For every product: Display the product ⏰ When Should We Use a Loop? A loop can be used when: The same task needs to be performed multiple times. For example: For every student: Display the student's name or: While the password is incorrect: Ask for the password again Different situations require different types of loops. 🔢 Types of Loops in JavaScript JavaScript provides different types of loops: for loop whi

本文内容来源于互联网,版权归原作者所有
查看原文