#4 Javascript Loops| Javascript Hindi Course For Beginners ( 2023 )

 
Why we use Loops ?
We use loops to do repeated actions.
// without loops // print 1 - 10 number on console console.log(1);console.log(2)console.log(3); console.log(4);console.log(5);console.log(6); console.log(7);console.log(8);console.log(9); console.log(10); // using loops for(let i = 1 ; i <= 10 ; i++){ console.log(i ) } // Look above line of code i have used loops reduce code // no need need to write 10 lines of console log 🤣
 

Types of loops in Javascript

  1. while
  1. do-while
  1. for
  1. forEach()
  1. map()
  1. for…in
  1. for…of
 

While Loop

while loop is most basic loop in javascript.
While loop runs a code block , as long as condition is true.
// Syntax while (condition) { // Block of code }
var i=8; while (i<10){ console.log("I is less than 10"); i++; } // Output /* I is less than 10 I is less than 10 ... 10 times */

Do While Loop

Do-while loop is slightly different from while loop.
Its has only one feature extra.
Do While loop code is executed at least once if condition satisfies .
If condition satisfies the code block will be executed like while loop.
// Syntax do { // Block of code } while (condition);
var i=7; do{ console.log("The value of i is " + i); i++; } while(i>7 && i<10); // Output /* The value of i is 7 The value of i is 8 The value of i is 9 */
 

For Loops

For loops and while loop work exactly same.
But For loops have much advance than while loop.
you can add initialization in for loop directly
you can add condition in for loop
you can also add final-expression in for loop
In case of while loop . you can only add condition
 
// Syntax for ([initialization];[condition];[final-expression]){ // Block of code }
for (let i=0; i<10; i++){ console.log("The Value of i is : " + i); } // Output /* The Value of i is 0 The Value of i is 1 ... The Value of i is 9 */
 
Currently we are skipping this topics , after learning object and array we will learn it
forEach()
map()
for…in
for…of
 
Questions:
  1. Print Even number upto 60 using for loop
  1. Given a number n Calculate the factorial of the number
  1. Write table for 19 using loop
  1. Write a program that will allow someone to guess a four digit pin exactly 4
times. If the user guesses the number correctly. It prints “That was
correct!” Otherwise it will print “Sorry that was wrong.” Program stops after the 4th attempt of if they got it right.
let pin = 0704; // Example output: // Please make your guess: // 4544 // Sorry that was wrong. // Please make your guess: // 4444 // Sorry that was wrong. // Please make your guess: // 0704 // That was correct!