Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                  ///////////////////////////////// Loops ////////////////////////////////

// Loops are used in programming to save time and effort, both in terms of the time and energy the programmer has to put in, and the efficiency of the program itself

// Loops repeat the same block of code until a specified condition is met, typically using or plugging in a different value each time

// Loops can be used to accomplish a variety of tasks, such as iterating through an array, etc. etc.____________

// The first type of loop we will discuss is a for loop:



  ///////////////////////////////// For Loops ////////////////////////////////

// As we visit each type of loop, you'll notice that they have very literal names

// For loops have the name 'for loop' because code is executed for as many iterations as specified

// An iteration is one complete loop. We make for loops execute for a specified number of iterations by declaring an iterator

/* The syntax for a for loop contains four major parts:
  
    for (statement 1; statement 2; statement 3) {
        code block to be executed
    }
    
          which you can also label as:
    
    for (iterator; condition; increment) {
        code block to be executed
    }
    

     1: The keyword for, followed by parenthesis and a pair of curly brackets
        - The parenthesis contain the three statements for loops require
        - The curly brackets contain the code to be executed during each iteration of the loop
        
     2: Statement 1/Iterator
        - Statement 1 is code that initializes the iterator for the for loop.
        - The iterator is our counting variable. It counts how many times we have looped through the for loop, so that the program knows when to stop looping.
        - The iterator will typically start at 0, unless we are working with arrays or something in which we want to start at a different index. 
        - Statement 1 is executed before the loop begins executing
        
     3: Statement 2/Condition
        - Statement 2 is a condition that the loop tests before beginning the next loop
        - The condition tests the iterator against some other value
        - Say, for example, we wanted to loop through the for loop 5 times. The iterator would start at 0, and the condition would test if the iterator is less than 5.
        - As long as the condition evalutes to true, the loop will execute
     
     4: Statement 3/Increment
        - Statement 3 is the final portion of the statements within the loop's parenthesis
        - Statement 3 is executed after the loop executes, and updates the iterator to signify that another loop has been completed
        - The iterator will typically be increased or decreased by 1, but it is not limited to changing the value by 1
        
      - Between each of the three statements, you must place a semicolon
    */

    // Example : The following for loop will loop 4 times and print the value of i to the console each time:

      for(i = 0; i < 4; i++){
        console.log("i is currently equal to " + i);
      }
      
      // In this for loop, 
      // Statement 1 is i = 0, meaning the loop will start with the iterator, i, at 0;
      // Statement 2 is i < 4, meaning the loop will execute as long as i is less than 4
      // Statement 3 is i++, meaning after each loop, the value of i will be increased by 1.

      // Check the console to see the statements printed during each loop.

        // In the beginning of working with loops, it's really useful to walk through each iteration of a loop by hand with pen and paper, to understand how the loop is working
        // On paper, for each iteration, you can record the value of the iteration variable, whether the condition is true, and the value of the iterator after it has been incremented/decremented/altered
        /* For example, I would write something like this on paper to walk myself through the forloop on line 68:
          Loop 1: 
              i = 0
              i < 4 = true
              i++ = 1
              Will the loop execute again? Yes
          
          Loop 2:
              i = 1
              i < 4 = true
              i++ = 2
              Will the loop execute again? Yes
           
          Loop 3:
              i = 2
              i < 4 = true
              i++ = 3
              Will the loop execute again? Yes
             
          Loop 4:
              i = 3
              i < 4 = true
              i++ = 4
              Will the loop execute again? No, because the condition i < 4 is no longer true after i was last incremented
              
              
         This is also a useful method for troubleshooting loops
          */

    // Loops can be used to accomplish more than simply printing things over and over. 
    
    // Loops can be used in any scenario where we would otherwise have to write many lines of similar code or lines performing the same task, but with altered values

    // For example, the next for loop will loop through the array 'cities' and capitalize each element

    let cities = ['baton rouge', 'new orleans', 'san antonio', 'miami', 'portland', 'san francisco', 'las vegas'];
    
    console.log(cities);  

    // By setting the condition to i less than the length of the cities array, we ensure that the for loop iterates through each array element 

    // Remember that the length of an array is the number of elements within the array

    // Additionally, remember that array indexes begin at 0, and we initialized our iterator, i, to be 0 in the beginning of the for loop. 

    // Do not get confused at the fact that there are 7 elements within the array, but the condition is proven false whenever i is equal to 7. This is because i begins at 0.

      for(i = 0; i < cities.length; i++){
        // here, we are using the iterator to access the element in the array according to which loop we are on.
        // if you are writing out the loop to better understand it, ensure that you understand the code within the loop is changing each iteration, from  cities[0] = cities[0].toUpperCase();, to cities[1] = cities[1].toUpperCase();, and so on
        cities[i] = cities[i].toUpperCase();
        console.log(cities[i]);
      }

    // To better understand how much our efficiency is increased by using loops, compare the forloop on line 117 to the alternative code below. Both perform the same actions, but the forloop is much quicker, both for us to program and for the computer to execute:
      cities[0] = cities[0].toUpperCase();
      console.log(cities[0]);

      cities[1] = cities[1].toUpperCase();
      console.log(cities[1]);

      cities[2] = cities[2].toUpperCase();
      console.log(cities[2]);

      cities[3] = cities[3].toUpperCase();
      console.log(cities[3]);

      cities[4] = cities[4].toUpperCase();
      console.log(cities[4]);

      cities[5] = cities[5].toUpperCase();
      console.log(cities[5]);

      cities[6] = cities[6].toUpperCase();
      console.log(cities[6]);

  // If you declare the variable used as the loop's iterator outside of the loop's declaration, you can omit statement 1, like so:

    let j = 0;
    for( ; j < 5; j++){
      console.log(j);
    }

  // Additionally, if the iterator is incremented/decremented/altered inside of the loop's code, statement 3 can be omitted from the loop's parenthesis aswell:

    for(i = 0; i < 10;){
      if(i < 5){
        console.log(i + " is smaller than 5");
      }
        i++;
    }


  ///////////////////////////////// For-In Loops ////////////////////////////////

// The next forloop related topic we will cover is for-in loops.

// Whereas forloops repeat a block of code a specified number of times, a for-in loop loops through the properties of an object

// The code within the loop is executed once per each of the object's properties

// For-in loops have two required parameters: var and object, where var is the property and object is the object name

// For-in loops behave similarly to forloops looping through arrays, but instead of looping through elements of an array, we are looping through properties of an object

// To visit each of the properties in an object, we would program our for-in loop like so:

  let chinchilla = {name:"Pushki", age:4, color:"gray", fluffLevel:"maximum capacity"};
  
  // Notice that the contents of the loop's parenthesis is much different than a typical for loop
  // The parenthesis tell the loop to loop through each property in the object 'chinchilla'
  
  for(property in chinchilla){
    console.log(chinchilla[property]);
  }
  // chinchilla.forEach(function(element) {  })
  // We can also include a specifier to loop through the properties of an object, whether it be let, const, or var; however this is not necessary, as you can see on line 185
  // The following three for-in loops will produce the same output as the loop on line 185:

  for(var prop in chinchilla){
      console.log(chinchilla[prop]);
    }

  for(const prop in chinchilla){
      console.log(chinchilla[prop]);
    }

  for(let prop in chinchilla){
      console.log(chinchilla[prop]);
    }
   
   ///////////////////////////////// For-Each ////////////////////////////////

// Foreach is used to visit each element within an array, and run a function on each element. 
// We've written for loops that visit each element in array previously, so the code below will show the conversion of a regular for loop to a foreach statement:

  let inventory = ['muffins', 'rolls', 'pastries'];
  let popularItems = [];

  for(i = 0; i < inventory.length; i++){
    popularItems.push(inventory[i]);
    console.log("New popular item added: " + popularItems[i]);
  }

// The code above is copying the contents of the inventory array to the popular items array. The code below performs the same task using the foreach method:

  //first we clear the popularItems array so the elements aren't duplicated
  popularItems = [];
  // next we use a forEach statement to push and print the elements
  inventory.forEach(function(item){
    popularItems.push(item);
    console.log("New popular item added: " + item);
  });

//Here is another example of a forEach loop. In this example, we have an array of arrays, each containing a date. We use a forEach method on the outside array, so that we can access each nested array. 
//In this example, we're using an arrow function rather than using the function keyword. Either is fine. 
//Inside the function, we're creating a new date object, and setting it with the numbers in each inside array. Then, we're printing out some information, using toLocaleDateString(). 
//The use of the num variable allows us to begin with the number 1, and increment it each time the message is printed out. 

let workshopDates = [[2024, 5, 6], [2024, 5, 8], [2024, 6, 7], [2024, 6, 10]];
let num = 1;
workshopDates.forEach((date) => {
  let workshopDate = new Date(date[0], date[1], date[2]);
  console.log(`Workshop ${num} is on ${workshopDate.toLocaleDateString()}`)
  num++
})


//For...of loops 

//For of loops are similar to forEach loops in that they can iterate over an array, but here are some key differences between for... of and for each:

/* 

* For of loops do not run a function | for Each loops must run a function 
* For of loops can iterate over anything that is iterateable (such as an array/strings etc) | For each loops are (mostly) only used on arrays
* For of loops can use 'break', 'continue', and 'return' statements | forEach cannot use these statements. 

*/

//Here is an example of a forEach loop:

let myNumbers = [1, 2, 3];
myNumbers.forEach((num) => {
  console.log(num * 5);
})

//Here is the same loop as a for...of loop:

let myNumbers1 = [1, 2, 3];
for (num of myNumbers1) {
  console.log(num * 5);
}


///////////////////////// Exercises /////////////////////////

//1. Squares: write a loop that iterates from 0 to 100. The loop will square the value of the current iteration, and print it to the console in this format: "__ squared is ___".
    // Declare an array named squareRoots. Within each iteration of the squares forloop, push the squared value into the squareRoots array.

//2. Square roots: Write a loop that iterates from 0 to 100. The forloop will iterate through the squareRoots array and print the following to the console with each iteration:
    // "The square root of x is y" , Where x is the value of the current element being accessed in the array, and y is the value of the square root

//3. Declare a new object representing a patient that contains the following elements: name, age, reason for visit, checked in (boolean), checked out(boolean)

//4. Write a function called printPatientInfo that loops through each property of the patient object and prints the property to the console
    // Call the function and check the statements printed to the console

//5. Create an array called colors that stores 5+ colors of your choice, as strings (can be written out or hex codes!). 
// Store the body of the webpage in a variable. 
// Create a for loop that iterates through the array. The loop should:
// - Create a new div (stored in a variable!)
// - Append the div to the body
// - Give the div a class name (this ensures that more than one div will be created!) like this: 
// nameOfDiv.className = "yourClassNameHere" (repace with your div name and a class name of your choice!)
// - Set the style.backgroundColor of your div to each element of the array (using [i]). 
// - Set the innerHTML of your div to each element of the array. 

//If your code has been done correctly, you should get a different colored band with the text for each color. 

/////////////////Extra Exercises:
//1. Create 7 empty paragraphs in HTML, give them ids from "0" to "6".

//Make an array that stores the colors of the rainbow, all lowercase (colors should be red, orange, yellow, green, blue, indigo, violet). 

//Make a for loop that loops through the array. Inside the curly brackets, create a variable that stores document.getElementByID and set your id to i (no quotes!)
//Underneath but still in the loop, set the innerHTML of your variable to the name of your array with [i].
//Underneath that but still in the loop, set the style.color of your variable to the name of your array with [i]. 

//Your loop should generate the names of the colors in those colors on your webpage. 

              
            
!
999px

Console