Wednesday, April 24, 2019

JavaScript(7)---Loops

Loops

  • loop is a programming tool that repeats a set of instructions until a specified condition, called a stopping condition is reached.
  • Instead of writing out the same code over and over, loops allow us to tell computers to repeat a given block of code on its own. 
The typical for loop includes an iterator variable that usually appears in all three expressions.
EX: A for loop contains three expressions separated by ; inside the parentheses:
  1. 1. An initialization starts the loop and can also be used to declare the iterator variable.
2. A stopping condition is the condition that the iterator variable is evaluated against— if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop.
3. An iteration statement is used to update the iterator variable on each loop.
Input:
for (let counter = 0(Indicates that it starts at 0); counter < 4(end with index 4); counter++(Increases by 1 after each loop) { console.log(counter); }
Output:
0
1 2 3

  • To loop through each element in an array, a for loop should use the array’s .length property in its condition.
EX:  Inside the block of the for loop, use console.log() to log each element in the vacationSpots array after the string 'I would love to visit '. For example, the first round of the loop should print 'I would love to visit Bali' to the console.
for (let i = 0; i < vacationSpots.length; i++ ){
  console.log('I would love to visit ' + vacationSpots[i]);
}
Notes:  Remember that arrays are zero-indexed, the index of the last element of an array is equivalent to the length of that array minus 1.
  •  the while loop. 
EX: Create a while loop with a condition that checks if the currentCard does not have that value 'spade'.
while ( currentCard != 'spade')
Math.floor(Math.random() * 4) will give us a random number from 0 to 3
  • do...while statement allows a piece of code to run at least once and then loop based on a specific condition after its initial run.
Unlike the whileloop, do...while will run at least once whether or not the condition evaluates to true.

  • The break keyword allows programs to “break” out of the loop from within the loop’s block.
What did I learn today? 
I learned how to connect codes in the language and know how to do specific jobs or get to specific goals.
What I'm doing tomorrow?
HIGHER-ORDER FUNCTIONS in Javascript

No comments:

Post a Comment