JavaScript For Loops

JavaScript For Loops

When you’re learning to program, the traditional first program is hello world. My traditional way to demonstrate looping in any given language is using a for loop to program 99 bottles of beer on the wall. So here you can see the result of 99 bottles of beer on the wall. And just trust me, it goes all the way to the end. In fact, we’ll take a quick look.

No bottles of beer on the wall, that’s where it ends. Let’s take a quick look at the code to see how I accomplished that. Now this script is directly inside the code because we really haven’t gotten to the point where we’re using an external JavaScript file to write inside the HTML. So I embedded it right here inside the body of the code at this point. So we have our script statement right here.

And then we have a for statement. And the first thing we have to do is initialize our variable. And typically you’ll actually see it initialized to 0 and counting up. But I like to the decrement for 99 bottles of beer on the wall just because it makes sense for this program. So I’m starting at a variable, which I’m initialising, naming I, and initialising to 99. While I is greater than 0, we will keep going and this decrements. So we declare it.

We state the condition. It has to be greater than 0. And we decrement the variable so that we don’t end up in an infinite loop, which is something you want to avoid. So then we just do our document.right. And we have our I in here to represent the number. Be careful when you do the I minus 1. If you don’t put it in parentheses, you might get an error.

I was getting an error when I didn’t have my I minus 1 in parentheses. And then after the loop is over, it’ll display no bottles of beer on the wall. Let’s show you what happens if we don’t have the parentheses. And then you can see, you get not a number.

That’s what NAN stands for– Not A Number. So you definitely want to keep your parentheses around the I minus 1. You should go ahead and try it if you haven’t done it in another language. Otherwise this is a simple demo of how the for statement works in JavaScript.

Leave a Comment

Your email address will not be published. Required fields are marked *