Categories
javascript

JavaScript Fundamentals: Loops

JavaScript Fundamentals: Loops

Why Use Loops?

  • Loops are a wonderful way to clean up your code!
  • When you need to repeat similar lines of code over and over again, you might want to consider implementing a loop to do the heavy lifting for you.
  • Loops prevent buggy code by consolidating the lines of code and making things easier to edit.
  • JavaScript uses two main kinds of loops: the for loop and the while loop.

For Loops

  • Accurate and precise way of repeating a function until the starting condition returns false.
  • If you know exactly how many times the loop should execute, use a for loop for its precision.
  • Looping over an array is a versatile and useful methodology.

TYPES OF FOR LOOPS:

  • for – loops through a block of code a number of times
  • for/in – loops through the properties of an object // not covered in this post
  • for/of – loops through the values of an iterable object // not covered in this post

BREAKING DOWN THE ELEMENTS OF A FOR LOOP:

//A BASIC FOR LOOP
//WILL PRINT TO CONSOLE EACH NUMBER FROM 0 -> 99, WITH A INCREASE OF +1 EACH ITERATION

for (let i = 0; i < 100; i++) {
 console.log(i);
}
forfor is the keyword to indicate a for loop.
let i = 0;Statement 1. The iterator.
Sets the variable that will be used in the loop. This statement is optional in JS if variables have already been set – but you must still include the semicolon with no statement before it.
i < 100;Statement 2. The conditional.
This sets the condition which needs to be met for the for loop to finish repeating.
Statement 2 is also optional if you include a break in the code to determine when the loop will end.
i++Statement 3. The post-fix operator.
Indicates the increment in which each iteration of the loop will impose upon the value, moving towards a point where the conditional would return false and break the loop.
i++ will add by one each time.
i- – will subtract by one each time I += 10 would increase by ten each time, etc.
Statement 3 is also optional if you set your value’s increments within the loop { }
console.log(i);This is the where you place any information that will be processed through the loop.
In this case, console.log(i) will print i’s value for every new incremental increase for every iteration of the loop.
 Don’t forget to use semicolons to separate each section of the for loop.
 

Examples of For Loops

FOR LOOPING OVER AN ARRAY:

• One of the most common uses of a for loop.
• When looping over arrays, it is common/best practice to give i (or whatever variable you want to call it, i is the most common) a starting value of 0 when initialized in the first statement of the loop. This ensures that you will loop over all elements of an array starting at index 0 upwards to array.length .
• Accesses each element of an array by their index numbers which can then be called to perform a computation. In the first example below, each element is simply printed to console with each iteration of the loop. In the second example, the loop contains a comparison operator and reassigns a pre-declared variable with each new ‘largestNum’ in the array.

//EXAMPLE OF HOW TO USE A FOR LOOP TO PRINT STRING ITEMS IN AN ARRAY TO CONSOLE:

const colors = ["blue", "yellow", "green", "pink"];
for (let i = 0; i < colors.length; i++) {
    console.log(colors[i]);
}

// EXAMPLE OF HOW TO USE A FOR LOOP TO FIND THE LARGEST NUMBER IN AN ARRAY:

const numArray = [1, 3, 2, 5, 10, 1];

function findLargestNum(numArray){
  let largestNum =null;                     //// in testing, I tried to initialize the largestNum variable without a value but 
  for(let i=0; i< numArray.length; i++){          //// because this instilled it with a value of undefined, it caused errors begin as it is more malleable.
    if (numArray[i] > largestNum){                 //////    in the code. I learned that null is a great value to 
      largestNum = numArray[i]                 ////// Alternatively, you could use the value of numArray[i] to start. 
    }  
 }return largestNum;
}
    

console.log(findLargestNum(numArray));

While Loops

• Easier to read because the control statement only contains a conditional.

If you’re not sure how many times the loop has to run but you do know when it should stop, use a while loop.

• Can be mistyped and/or created in a way in which the condition will always return true which results in an infinite loop, an unfortunate bug that can cause major problems in a code.

let number = 0;       // while loops declare the iterator variable before the loop begins
while (number <= 10) {      // while (condition is true) {
    console.log(number);
    number++;      // increment is defined at the end of the loop
}
let number = 0;  Creates variable for number with value of 0
while (number < 11){Creates while loop with a conditional
Will loop as long as the number value is less than 11.
number = number + 1; can also be written as number += 1 or number ++;Indicates that the number value will increase by 1 each iteration of the loop.
  
LeaNakamura's avatar

By LeaNakamura

I'm a Brooklyn-based web development student, musician and textile artist originally from Maui, Hawaii.

One reply on “JavaScript Fundamentals: Loops”

Leave a comment

Design a site like this with WordPress.com
Get started