Loops in JavaScript.

in #hive-1693212 years ago


You certainly can't know JavaScript or any other programming language without knowing about Loops.

Loops are very useful when you want to run the same block of code over and over again while using a different value each time.

In JavaScript, loops are used to perform repeated tasks based on a condition. Conditions usually take the form of booleans which return either true or false . A loop will continue running until the defined condition returns false .

JavaScript supports mainly four types of loops :

  • for loops
  • for/of loops
  • for/in loops
  • while loops

And I'll be explaining each of them 🙂

for Loops

Syntax:

for ( expression1 ; expression2 ; expression3 ; ){
  // Block of code to run
}

By using the for statement, you'll create a loop with three optional expressions just as in the syntax above.

Expression1 is executed before the block of code is run and it's used to initialize the variable which would be used in the loop.

Expression2 is used to set the condition for the loop to run. If it returns true, the loop will continue but if it returns false, the loop terminates.

Expression3 is used to update the initial value of the initial variable after every successful code execution. It can do a positive or negative increment or any other thing.

Example:

let count = "" ;

for ( let i = 0 ; i <= 5 ; i++){
  count+= i + " " ;
}

console.log( count ); // Prints 1 2 3 4 5

The code above creates a loop that counts from 1 to 5. The value of the initial variable is set to zero; let i = 0 ; , then the value is continuously increased by one provided the condition which requires that the value doesn't exceed 5, is met .

for/of Loops

Syntax:

for( variable of interable ){
  // Block of code to run
}

The for/of loop is used to loop through the values of an interable object.
By using this loop, you can be able to interate over interables such as strings, arrays, maps, sets and more.

From the syntax above;

  • variable accesses the items in the interable. At the start of the loop, it holds the value of the first property of the interable and for every interation, the value of the next property is assigned to the variable.

  • interable is the object with interable properties you want to loop over.

Example:

Looping over a string:

let username = "charlrific" ;
let output = "" ;

for ( let x of username ){
  output+= x + " " ;
}

console.log(output); // Prints c h a r l r i f i c

Looping over an array:

const numbers = [1, 2, 3, 4, 5];
let output = "" ;
for ( let x of numbers ){
  output+= x ;
}
console.log(output);
 // Prints 15

for/in Loops

Syntax:

for ( key in object ){
  // Block of code to run
}

The for/in loop in JavaScript allows you to iterate over all property keys of an object. In each iteration of the loop, a key is assigned to the key variable. The loop continues for all object properties.

From the syntax above;

  • key is used to access the value of the key in the object which would be the index numbers.
  • object is the object of which properties we wish to loop through.

Example:

const user = {
    username : "charlrific", 
    name : "Charles", 
    reputation : 59 
 };

let output = "" ;

for ( let x in user ){
  output+= user[x] + " " ;
}

console.log( output );
// Prints 'charlrific Charles 59' 

for/in Loops can also loop over the properties of an array or a string.

Example:

const numbers = [ 1, 2, 3, 4, 5];
let sum = "" ;
for ( let x in numbers ){
  sum+= numbers[x] ;
}

console.log(sum); // Prints 15

while Loops

Syntax:

while (condition) {
  // Block of code  to run
}

The while loop is just like the for loop without the first and third expressions. This loop would continue to execute a block of code as long as a specified condition is true.

Example:

let output = "" ;

while ( i <= 5 ) {
  output += i + " " ;
  i++ ;
}

console.log(output); // Prints ' 1 2 3 4 5 '

do/while loop is a variation of the while loop. But in this case, the code will always be executed once before the condition is tested.

Syntax:

do {
// Block of code to run
}
while ( condition ) ;

Example:

let output = "" ;
let i = 0 ;

do {
output = i + " " ;
i++ ;
}
while ( i <= 5 ) ;

console.log(output); // Prints ' 1 2 3 4 5 '

When using loops, it's very important that you include the code to update the variable used in the condition, for instance;i++, otherwise the loop will never end!

Loops are very important and useful tools in JavaScript and knowing just the right way to apply them can make your coding experience a lot better🙂.

Thanks for stopping by!❤️

Sort:  

🍕 PIZZA !
@charlrific! The Hive.Pizza team manually upvoted your post.

Please vote for pizza.witness!

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

You gave me a good refresher on loops in javascript. it has been a while I touched it though but although I had previously understood the process. You gave great examples bro.

Thanks a lot boss! I'm really glad you found my article useful.
Thanks for visiting!❤️

Congratulations @charlrific! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You received more than 250 HP as payout for your posts, comments and curation.
Your next payout target is 500 HP.
The unit is Hive Power equivalent because post and comment rewards can be split into HP and HBD

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Support the HiveBuzz project. Vote for our proposal!
Thank you for sharing this post on HIVE!

Your content got selected by our fellow curator tibfox & you received a little thank you upvote from our non-profit curation initiative. Your post will be featured in one of our recurring curation compilations which is aiming to offer you a stage to widen your audience within the DIY scene of Hive.

Next time make sure to post / cross-post your creation within the DIYHub community on HIVE and you will receive a higher upvote!

Stay creative & hive on!