Tuesday, July 15, 2014

JavaScript: Loops

For loop: For variable i, if i is less than 5, then add 1. i = i + 1 will be solved on the right, then assigned to the left. So i + 1 is done, then if i is 1, 2 will be assigned on the left as the new value of i. Console.log simply writes the result, which would be 1, 2, 3, 4, and 5.
var i;
for (i = 0; i < 5; i = i + 1)

For loop using "++" . The only difference here is the shortcut ++ which is equivalent to i + 1.

for (var i = 0; i < 3; i++)

For-in loop: will iterates over enumerable properties of an object. Enumerable properties are non-shadowed, user-defined property (including inherited properties)-- not built-in properties, for ex. toString. They follow this formula: for (variablename in object){statement or block to execute}. This is a great resource for more on these specifically, their exceptions, and other nitty gritties.

var aProperty;
document.write("Something's Object Properties
"); for (xProperty in Something) { document.write(xProperty); } document.write("Exiting loop.");

While Loop: If i is 99, and if that value of i (99 currently) is greater than 0, run this code. This code says to print "99 red balloons," then subtract 1 from i.. so now i is 98. And loop back to the top. So, now i is still greater than 0, write "98 red balloons," subtract one.. and so on..

var i = 99;
while (i > 0)
    text += (i + " red balloons");
    i -= 1;

Do while loop: This is essentially the same and a variant of the while loop. If i is 0, then print out "I know how to count! 1" and add 1 to i, so i will be 1 now.. and the following will now be printed "I know how to count! 2," and so on.. until i hits 10. So, the last number actually printed will be 9, because after 9 is printed, you will add one and the code will exit because i is no longer less than 10.

do {
    var i = 0;
    text +=  "I know how to count! " + i;
while (i < 10);

NOTE: The difference between the while loop and the do while loop is that in the do while loop, then the code block is executed AT LEAST ONCE before the condition is tested no matter if it is true or false (because the while is at the end after execution). The while loop will only execute for the scenario if it is true.