JS loops dos and don’ts

Photo by Mad Fish Digital on Unsplash

Okay.

You are a JavaScript developer, and you write loops.

Have you ever been curious why you keep messing up your loops?

In this article, I will take you through some dos and don’ts in JavaScript loops.

Yeah.

What are Loops?

Loops are used for repeating blocks of code until certain conditions are satisfied.

The Dos and Don’ts

1. Usage of the let keyword

Don’t do this!

The code above shows undefined because the variable is initialized with the let keyword. Let is block-scoped. The variable can only be used within the loop.

Do this!

If you want to use the counter variable outside the loop, then declare the variable outside the loop with the let keyword.

You can also use the var keyword to declare the variable. var declaration is function scoped. It is always visible outside the loop.

2. Exceeding the bounds of an array

This happens when you reference the index that is greater than or equal to the length of the array

Oh!, are you lost?

Let me make this clear!

The example code below has an array of num = [1,2,3,4], the length of the array is 4 but the highest index is 3. You exceed the bounds of the array when you try to get the value of num[4] or num[5].

Don’t do this!

The code snippet above shows you are trying to reference the 5th element of a 4 element array. This will lead to the bounds of the array being exceeded.

Do this!

3. Off-by-one error

Don’t do this!

The user here is trying to print out five stars but ended up printing out 6 stars.

Why?

Okay, check out the code below.

Do this!

4. Declaration!, not initialization

When writing a while loop don’t forget to initialize the variable used in the condition of the loop.

Don’t do this!

The code above shows the variable used in the condition is only declared, but not initialized.

Do this!

5. Infinite loop

Do you know why you keep running into a loop that just keeps running and never terminates?

Have you ever ask yourself, what am I doing wrong?

Well, listen!, as I walk you through it.

You will always run into an infinite loop if;

i. The condition in your loop is always evaluating to true

ii. You forget to update the increment variable

iii. There is no terminating condition

Yeah!, Thanks for reading to the end. What is your thought?.

I hope you find this useful. Leave your suggestion in the comment box below. I will be waiting to reply.

I am a freelance writer and a front end Web developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store