Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

What is the difference between While loop and for loop ?

javascript

Best Answer RhetoricalRuvim, 09 June 2014 - 07:48 AM

It is possible to use both for either tasks, but it is natural to use 'for' for one type of work and 'while' for another, as WingedPanther said.

Consider this code:

var count= 0; 
for (; count < 5;){ 
  alert ("hi, this is the " + count + "-th time I am annoying you with this message box"); 
  count++; 
} 
It is just the same as this while loop:
var count= 0; 
while (count < 5){ 
  alert ("hi, this is the " + count + "-th time I am annoying you with this message box"); 
  count++; 
} 
; the only difference is that, in the while loop, you don't need the semicolons (';' symbols) around the condition. So why use 'for' loop if you can just use 'while' ?

The thing with 'for' loops is that oftentimes, when used as WingedPanther mentioned, they are much more natural to read. Would you rather read the above examples, or this?:
var count; 
for (count= 0; count < 5; count++){ 
  alert ("hi, this is the " + count + "-th time I am annoying you with this message box"); 
} 
Of course, the statement to the left of the first ';' (the statement: count= 0) can be anything that needs to be executed at the beginning of the 'for' loop. Likewise, the statement to the right of the second ';' can also be anything but that statement is executed after each loop iteration (in our case, we need to count++, but theoretically it can be anything).

JavaScript is that way, and I believe C/C++ is too, that you can use a 'for' loop in place of a while loop, like my first example. Some languages, however, restrict how you can use 'for' loops, like in Ruby:
for count in 1...10 
  print "Hello World!\r\n" 
end 
; in that case, 'count' is going to go from 1 to 10 (exclusive; use '..' in place of '...' for inclusive), and you cannot do this:
for count in 1...10 
  count = 1 
  print "Hello World!" 
end 
; it'll change 'count' to 1, but it'll change it right back to 3 or 4 or whatever the next number should be, and it will execute the loop exactly 9 times, no matter how much you change the count in between. On the other hand, JavaScript and C/++ 'for' loops allow more control, in a way (note: this is a never-ending loop):
for (count= 0; count < 10; count++){ 
  count= 1; 
  document.write ("Hello World!"); 
} 
This last piece of JavaScript is theoretically never supposed to stop running because you always set the count back to 1 whenever the loop runs an iteration.

The not-so-nice thing about JavaScript's approach to 'for' loops is the possibility of crashing your code if you forget to make a way out of the loop. The nice thing about it, though, is when doing something where the array or list, etc., you are working on changes, as in removing all text nodes from an element:
var elem= document.getElementById ("/* put an element's id here */"); 
var i; 
for (i= 0; i < elem.childNodes.length; i++){ // Iterate through all child nodes of element. 

  if (elem.childNodes[i].nodeType != 3) continue; // Continue if not text node. 

  elem.removeChild (elem.childNodes[i]); // Remove the text node. 

  i--; // The array will be shifted starting at index i and on, so the NEXT index need to be processed is what is now 'i', not 'i + 1' (what it will be next). 

} 
This last piece of code goes through a DOM element (e.g., a DIV or something) and removes all non-child text from it. The removeChild () method modifies the childNodes node list, starting from right where the counter 'i' is, so it would be nonsense to not include the 'i--' statement.

Kind of like this:
say, childNodes is like this: [a DIV element, an IMG element, a text node, and another DIV element, another IMG element]; 

the code gets to the text node, and 'i' = 2 into childNodes list 
removeChild removes node with index of 2 (the text node), and array shifts and becomes: 

[a DIV element, an IMG element, another DIV element, another IMG element]; 

Logically, the next node to check is the 'another DIV element' node, which is NOW index 2 because the array was shifted. 

The for loop continues, and 'i' is now 3 (because it was 2 last, and the 'i++' part inside the 'for' parentheses makes 'i' greater). This way, we just skipped checking the next node and jumped ahead to the one after the next! 
The i-- helps correct that; it makes 'i' one smaller, so that, when the loop continues and makes it one larger, then 'i' will be at the next node, and not the one after that. It helps make up for the array shift.

If something like this was to be done in a language that resets the counter variable back to what it is "supposed" to be, then some work-around needs to be done. There is such keyword as 'redo' in Ruby, but consider this:
arr = [1, 2, 3, 4] 
number_to_stop_at = 2 # Let's do something to index 2. 
for i in 0...arr.length 
	if i == number_to_stop_at 
		arr.delete_at i # Delete i-th array element. 
		number_to_stop_at = -1 # Never stop again (i will never == -1). 
		redo # Continue, but do not increment i. 
	end 
	print "number: " + arr[i].to_s + "\r\n" 
end 
; even though the number of elements in the array changed from 4 to 3, it still will print 'number: ...' 4 times (with a blank in place of the number on the 4th print), not 3 times.

Back on-topic; basically, 'for' loops are good if you know the array won't change (e.g., in a language like Ruby), and they're also good if the array will change but there is enough control to change the number of iterations (e.g., JavaScript, C++). If the language gives you enough control, you can even use it in place of the 'while' loop. However, as WingedPather explained, it is better to use 'while' for non-number-based iterations, and to use 'for' for number-based iterations. And sometimes, in some languages, you may even have to go around the 'for' loop even for number-based iterations (like the array-modifying example). Go to the full post


This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1 B13

B13

    CC Regular

  • Member
  • PipPipPip
  • 28 posts

Posted 08 June 2014 - 11:42 PM

I know ,this question is very funny for experts but for a kid like me many things.  :c-blink: 

What are the difference between While loop and for loop ? I cannot catch it . It seems to me that both are same.  


:confused:


#2 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts

Posted 09 June 2014 - 04:57 AM

It depends a bit on the language, but in general, the idea for a for loop is to perform an action a fixed number of times. For example, if you know you want to print something exactly 5 times at the start of the loop, then a for loop is the natural choice.

 

A while loop is generally used when you do NOT know how many times you want to perform the action at the start of the loop. For example, if you want to get input until the user enters a valid phone number, or chooses "quit", etc.


Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#3 B13

B13

    CC Regular

  • Member
  • PipPipPip
  • 28 posts

Posted 09 June 2014 - 06:47 AM

Below codes are the example of while loop which runs 10 times . Then why is it not for loop?

 

var count = 0;
       
while (count < 10) {
    document.writeln("looping away!");


    count++;

 

It depends a bit on the language, but in general, the idea for a for loop is to perform an action a fixed number of times. For example, if you know you want to print something exactly 5 times at the start of the loop, then a for loop is the natural choice.

 

A while loop is generally used when you do NOT know how many times you want to perform the action at the start of the loop. For example, if you want to get input until the user enters a valid phone number, or chooses "quit", etc.

 


:confused:


#4 RhetoricalRuvim

RhetoricalRuvim

    JavaScript Programmer

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1311 posts

Posted 09 June 2014 - 07:48 AM   Best Answer

It is possible to use both for either tasks, but it is natural to use 'for' for one type of work and 'while' for another, as WingedPanther said.

Consider this code:
var count= 0; 
for (; count < 5;){ 
  alert ("hi, this is the " + count + "-th time I am annoying you with this message box"); 
  count++; 
} 
It is just the same as this while loop:
var count= 0; 
while (count < 5){ 
  alert ("hi, this is the " + count + "-th time I am annoying you with this message box"); 
  count++; 
} 
; the only difference is that, in the while loop, you don't need the semicolons (';' symbols) around the condition. So why use 'for' loop if you can just use 'while' ?

The thing with 'for' loops is that oftentimes, when used as WingedPanther mentioned, they are much more natural to read. Would you rather read the above examples, or this?:
var count; 
for (count= 0; count < 5; count++){ 
  alert ("hi, this is the " + count + "-th time I am annoying you with this message box"); 
} 
Of course, the statement to the left of the first ';' (the statement: count= 0) can be anything that needs to be executed at the beginning of the 'for' loop. Likewise, the statement to the right of the second ';' can also be anything but that statement is executed after each loop iteration (in our case, we need to count++, but theoretically it can be anything).

JavaScript is that way, and I believe C/C++ is too, that you can use a 'for' loop in place of a while loop, like my first example. Some languages, however, restrict how you can use 'for' loops, like in Ruby:
for count in 1...10 
  print "Hello World!\r\n" 
end 
; in that case, 'count' is going to go from 1 to 10 (exclusive; use '..' in place of '...' for inclusive), and you cannot do this:
for count in 1...10 
  count = 1 
  print "Hello World!" 
end 
; it'll change 'count' to 1, but it'll change it right back to 3 or 4 or whatever the next number should be, and it will execute the loop exactly 9 times, no matter how much you change the count in between. On the other hand, JavaScript and C/++ 'for' loops allow more control, in a way (note: this is a never-ending loop):
for (count= 0; count < 10; count++){ 
  count= 1; 
  document.write ("Hello World!"); 
} 
This last piece of JavaScript is theoretically never supposed to stop running because you always set the count back to 1 whenever the loop runs an iteration.

The not-so-nice thing about JavaScript's approach to 'for' loops is the possibility of crashing your code if you forget to make a way out of the loop. The nice thing about it, though, is when doing something where the array or list, etc., you are working on changes, as in removing all text nodes from an element:
var elem= document.getElementById ("/* put an element's id here */"); 
var i; 
for (i= 0; i < elem.childNodes.length; i++){ // Iterate through all child nodes of element. 

  if (elem.childNodes[i].nodeType != 3) continue; // Continue if not text node. 

  elem.removeChild (elem.childNodes[i]); // Remove the text node. 

  i--; // The array will be shifted starting at index i and on, so the NEXT index need to be processed is what is now 'i', not 'i + 1' (what it will be next). 

} 
This last piece of code goes through a DOM element (e.g., a DIV or something) and removes all non-child text from it. The removeChild () method modifies the childNodes node list, starting from right where the counter 'i' is, so it would be nonsense to not include the 'i--' statement.

Kind of like this:
say, childNodes is like this: [a DIV element, an IMG element, a text node, and another DIV element, another IMG element]; 

the code gets to the text node, and 'i' = 2 into childNodes list 
removeChild removes node with index of 2 (the text node), and array shifts and becomes: 

[a DIV element, an IMG element, another DIV element, another IMG element]; 

Logically, the next node to check is the 'another DIV element' node, which is NOW index 2 because the array was shifted. 

The for loop continues, and 'i' is now 3 (because it was 2 last, and the 'i++' part inside the 'for' parentheses makes 'i' greater). This way, we just skipped checking the next node and jumped ahead to the one after the next! 
The i-- helps correct that; it makes 'i' one smaller, so that, when the loop continues and makes it one larger, then 'i' will be at the next node, and not the one after that. It helps make up for the array shift.

If something like this was to be done in a language that resets the counter variable back to what it is "supposed" to be, then some work-around needs to be done. There is such keyword as 'redo' in Ruby, but consider this:
arr = [1, 2, 3, 4] 
number_to_stop_at = 2 # Let's do something to index 2. 
for i in 0...arr.length 
	if i == number_to_stop_at 
		arr.delete_at i # Delete i-th array element. 
		number_to_stop_at = -1 # Never stop again (i will never == -1). 
		redo # Continue, but do not increment i. 
	end 
	print "number: " + arr[i].to_s + "\r\n" 
end 
; even though the number of elements in the array changed from 4 to 3, it still will print 'number: ...' 4 times (with a blank in place of the number on the 4th print), not 3 times.

Back on-topic; basically, 'for' loops are good if you know the array won't change (e.g., in a language like Ruby), and they're also good if the array will change but there is enough control to change the number of iterations (e.g., JavaScript, C++). If the language gives you enough control, you can even use it in place of the 'while' loop. However, as WingedPather explained, it is better to use 'while' for non-number-based iterations, and to use 'for' for number-based iterations. And sometimes, in some languages, you may even have to go around the 'for' loop even for number-based iterations (like the array-modifying example).

Edited by RhetoricalRuvim, 09 June 2014 - 07:51 AM.

Regards,
RR

#5 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts

Posted 09 June 2014 - 10:26 AM

In all languages that support them, you can use a while loop to perform the same logic as a for loop. The for loop is just more concise, and its use serves as an indicator that there probably won't be any funny logic applied to the loop variable. Using a while loop generally indicates that there may be something funny going on, or that the number of loops is unknown.


Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download