Loops

While Loops

Definition and Syntax

A while loop is a way to go through a block of code until a certain condition is met. A while loop can run an infinite number of times, so it is important to be careful when using it. It is best used when you don’t know how many times a piece of code will need to be run.

The basic syntax is:

while (condition) {
  // code to do
  // code to affect condition
} 

Example

while (answer != 'apple') {
  alert('please help us unscramble the letters to make a word.')
  answer = prompt('unscramble: \'ppela\'. What world could that be? Hint: it\'s a fruit')
}

For Loops

Definition and Syntax

A for loop is a way to iterate something a specified number of times. We use this when we know how many times we will need to loop something. They are often used to iterate over arrays and objects.

The basic syntax is:

for (let i = 0; i < 100; i++) {
  //code to run on each i
}

Example

let healthcareExchange = [
  {
    name: 'Cigna',
    premium: '$200/month',
    deductible: '$6,000'
  },
  {
    name: 'Aetna',
    premium: '$300/month',
    deductible: '$4,500'
  },
  {
    name: 'UnitedHealthcare',
    premium: '$250/month',
    deductible: '$5,000'
  },
]

for (i = 0; i < healthcareExchange.length; i++) {
  console.log(`${healthcareExchange[i].name} costs ${healthcareExchange[i].premium} with a ${healthcareExchange[i].deductible} deductible.`)
}

For In Loops

Definition and Syntax

A for in loop is very similar to a for loop, but it is only for looping through an array or object.

The basic syntax is:

for (let i in collection) {
  // code to apply to each item in the array
}

Example

Using the same array healthcareExchange we established before, we can run this for in loop to get the exact same output as we did previously:

for (let i in healthcareExchange) {
  console.log(`${healthcareExchange[i].name} costs ${healthcareExchange[i].premium} with a ${healthcareExchange[i].deductible} deductible.`)
}

How to loop through an array

You can use a for loop to traverse objects in an array.

Example:

var step;
for (step = 0; step < 5; step++) {
  [1, 2, 3, 4, 5]
}


  // Runs 5 times, with values of step 0 through 4.
  console.log(numberedList[step]);
}

[^fn]

[^fn] March 13, 2018

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array