2

So I have a fairly good amount of experience in coding. I've dabbled in Basic, HTML, Javascript, C, and C++, though the ones I've been using most recently are HTML and Javascript.

I am incredibly familiar with the for-loop. I've used it many times to loop through arrays, to operate recursive functions, etc. I know what it does and how to use it, but my question is about how it works.

Premise

In most languages, the basic syntax of a for loop is such:

var upperLimit = 10;

for(var i = 0; i < upperLimit; i++) {
    /*Code to be executed*/
    console.log(i);
}

In Javascript, this will output the numbers from 0 to 9 in the console.

I know that the parentheses contains 3 parts, each separated by semicolons.

  • The first is the initialization, which typically sets up the variables to be used to loop the statements.
  • The second is the condition, which runs before any of the code between the curly braces is executed. If it results in a True, the code is executed. Otherwise, the for-loop stops.
  • The third is the increment, which contains the last bit of code to be executed in the loop, and, by extension, the last thing executed before the next condition check.

Question

So, again, my question is how strict are these definitions?

The initialization's definition doesn't allow for much. It just says that that line is executed once, it's executed before anything else in the loop, and it's scope is limited to the loop. I can't think of much else you'd want to put in that position other than an iterative variable.

But what about the other two? I've seen codes where the condition is simply a variable, and as long as it's positive (since positive numbers taken as a boolean just covert to true), the loop continues.

Then there's the increment, which seems to be the loosest of these parts. Is it really just the last thing to be executed in a code, or does it explicitly need to iterate the variable declared in the initialization? It seems to be the former for the languages I'm familiar with.

For example, I decided to make a non-standard for-loop, and I came up with this routine:

var numbers = [0,1,2,3,4,5,6,7,8,9];
        
for(var i = 0;
    numbers.length;
    console.log(numbers.pop())) {}

It runs exactly as I expected: It outputs each member of the numbers array in the console in descending order, leaving an empty numbers array afterwards, and it's done using what is basically an empty for-loop.

Ending

So are my assumptions correct? If so, are there any practical applications for using a for-loop in a format apart from the one I wrote at the top of this question (possibly closer to he second format)?

Community
  • 1
  • 1
  • The third part is not an increment, it is an instruction run at the end of each loop, so basically you can put whatever you want here as long as it is an instruction (like what you did in your sample). This is also available in many other languages btw. If you want to understand how it works, I suggest you to study some compilation basics. – bviale Jul 23 '15 at 14:38
  • You still followed the definition; variable to be used, condition, instruction – FirebladeDan Jul 23 '15 at 14:38
  • Your assumptions look mostly correct, but there's an excellent reason to not do something like your non-standard loop: it's not obvious what you're doing, or why. Incidentally, you can put multiple variables in the first section (`for(var a=0, b={}, c=[1,2]; ...`) – Joe Jul 23 '15 at 14:38
  • 3
    *it's scope is limited to the loop* -- wrong (in JavaScript). – Pointy Jul 23 '15 at 14:40
  • Why not just read [the manual](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement)? – hindmost Jul 23 '15 at 14:40
  • so what is question? – Grundy Jul 23 '15 at 15:00

3 Answers3

1

Before all, you give a array

var numbers = [0,1,2,3,4,5,6,7,8,9];

The codes below is a correct for loop.

for(var i = 0;
    numbers.length;
    console.log(numbers.pop())) {}

Javascript defined for like this

for ([initialization]; [condition]; [final-expression])
   statement

For you code initialization is 'var i = 0', and execute once at start of loop.

The condition is 'numbers.length', and value is 10. When a number not 0, Javascript will convert it to boolean true. So condition is true.

The final-expression is 'console.log(numbers.pop())'. When execute 'numbers.pop()', numbers.length change to 9. But it still is true.

At second time, condition will return true again. The final-expression is execute too.

Until numbers.length become 0, Javascript convert it to boolean false. The loop will end.

Eric Zeng
  • 135
  • 5
0
  • The scope of the initialized variable is not limited to the loop, it's valid for the whole function (undefined before that line). You can initialize multiple variables using a comma. for (var i=0, j=1; i < 10; i++)
  • The second part, anything that evaluates to a truthy value will cause the loop to keep going:
    • Truthy: 1, -1, true, "something", {a: 2}
    • Falsey: 0, false, null, undefined
    • You could omit this and rely on a break in your code
  • The third part just lets you update the looping variable, you could omit it and do it within the for loop body.

Here's an answer that provides a nice way to loop that is non-standard, and comes with caveats, please see the link.

var list = [{a:1,b:2}, {a:3,b:5}, {a:8,b:2}, {a:4,b:1}, {a:0,b:8}];

for (var i=0, item; item = list[i]; i++) {
  // Look no need to do list[i] in the body of the loop
  console.log("Looping: index ", i, "item" + item);
}
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

In most languages, the basic syntax of a for loop is such:

for(initialization; condition; iteration) {
    /*Code to be executed*/
}

Both three are usual expressions and you can use any valid expressions here:

for(
  var i=arr.length, othercond=true; 
  i; 
  othercond?i--:i++, console.log(i),updateothercond()
);
vp_arth
  • 14,461
  • 4
  • 37
  • 66