TIL 23: javascript 7

Standard

For loops:

  • loops allow the same bit of code to be run multiple times
  • For loops are the most common kind in javascript
  • the declaration format is: for ([initialisation]; [condition]; [final-expression])
  • the initialisation step only executes once, before the loop starts. Generally it is used to set up the loop variable
  • the condition statement is evaluated at the start of every loop, and the loop is only executed if this condition evaluates to true
  • the final-expression is executed at the end of each loop, before the next condition check, and usually increments or decrements the loop counter
  • e.g. for(var i = 0; i < 5; i+=2) { myArray.push(i)];} would result in [0, 2, 4]
  • For loops are often used to iterate through arrays, e.g. for(var i = 0; i < 5; i++) {console.log myArray[i]; }
  • nested for loops are used to loop through multi-dimensional arrays, e.g.

code

While loops:

  • as the name suggests, runs ‘while’ a specified condition is true
  • var i = 0; while (i < 5) { myArr.push(i); i++ }
  • note that the counter variable, i, has to be declared outside of the loop – while (var i < 5) would try to redeclare it on every loop
  • also note the need to increment the counter within the loop – if you forget this you’ll enter an infinite loop!
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s