For Statements

Back

Preview

Before attending class, students should:

  1. Brush up on Arrays, if needed
  2. Skim this lesson document and take note of new syntax and vocabulary. It is not recommended that you complete the exercises.

Learning Goals

  • Explain the concept of a loop
  • Implement syntax for for statements for a variety of situations, including looping with an Array

Vocabulary

  • code block
  • condition
  • for statement
  • initialization

Warm Up

Write 1-2 sentences to explain the code snippet below, using as many technical vocabulary terms as possible.

var emails = [
  "kaitlyn@turing.edu",
  "justina@turing.edu",
  "amy@turing.edu",
  "launa@turing.edu",
  "nikki@turing.edu",
  "naomi@turing.edu"
];

Discovery

Work through the activity that follows to practice reading unfamiliar code and working to make sense of it. After this, you will receive direct instruction and acquire some vocabulary to help you speak about these concepts - it’s ok to experience some confusion and discomfort during this activity. To get the most out of this time, monitor your level of type of struggle, and communicate openly with your peers to support each other in your learning.

Reading a for loop (small groups)

  • The person with the longest Starbucks order should screenshare (drive). Open this replit and click "fork". Make sure the font size is big enough for everyone else in the Breakout room to easily see. From here on out, the other partner can serve as a Navigator and provide directions so the Driver can keep the replit screen up.
  • Run the code in the replit. Give everyone in the group some time to read through the code for each for statement and identify the portion of the output that belongs with it. Discuss: What do you notice? Work to identify which piece of the code corresponds to a change in the output.
  • If questions or wonderings such as "I wonder what would happen if we did X instead of Y...?" - there is nothing stopping you from trying that out, and finding the answer right now! You can edit the existing code, copy-and-paste code snippets then modify, or write something out yourself. You should do those explorations as a group and have your Driver do that on their screenshare.


for statement Explained

In our live class, we will dissect the code snippet that follows:

for (var i = 0; i < 4; i++) {
  console.log(i);
}

// --> 0
// --> 1
// --> 2
// --> 3
for ([initialization]; [condition]; [final-expression]) {
  [statement]
}
  • A for statement creates a loop. This provides the opportunity to run one line of code many times.
  • initialization: this initializes a counter variable that can keep track of how many times the loop has run. This expression is evaluated one time - before the loop begins
  • condition: this is evaluated before each loop iteration. If condition evaluates to true, the code in the loop runs. If it evaluates to false, the loop ends.
  • final-expression: this is evaluated after each loop iteration. It is usually used to increment the counter variable. If nothing ever changes in regards to the condition, the loop will run infinitely.
  • statement: this executes every time the condition evaluates to true. Almost always, it is wrapped in curly braces {}, making it a code block. As many lines of code as neccesary can be written inside the code block.

Common Questions

  • Why is the counter variable named i in most examples I see? Any valid JavaScript variable name can be used, but i is a convention in for loops, and it stands for index.
  • Are these semi-colons really necessary? Can I use commas instead? Use of semi-colons to separate the three expressions provided to the for statement is mandatory.


Practice

Explaining Code

  • Choose one of the for statements that was in the replit used for the Discovery activity.
  • To review and solidify what we just talked through as a class, prepare a verbal or written explanation of what your selected for statement does, in as much detail as possible. Make note of things you find yourself asking yourself, wondering, or feeling confused about.
  • Be prepared to share out your explanation or a specific question that you came up with during this time.


Writing Code (Pairs)

For these tasks, utilize your notes but do not, under any circumstance, copy-and-paste code. It's recommended you write the code in a new replit file.

Determine a Driver and Navigator for the first challenge. The Driver should screenshare their replit window.

  • Challenge #1: Write code that will print out the numbers 12-18.

Switch Driver-Navigator roles.

Be ready to screenshare and explain your code if you are called on.


Loops and Arrays

Many times, we use for statements to loop through Arrays and do something to or with each element in an Array. The following code snippet models an example:

var fruits = ['apples', 'oranges', 'bananas'];

for (var i = 0; i < fruits.length; i++) {
  console.log("I have some " + fruits[i]);
}

Investigating Code (Pairs)

For this task, the Driver should fork this replit, then the Navigator should guide with these directions:

  • Print out to the console fruits.length and notice the output, and try to make sense of where that came from. Keep what you learned by doing that in mind, keep or delete that code, and continue.
  • Change fruits.length to 3. Re-run the code - has the output changed?
  • Change fruits[i] to [i]. Re-run the code - has the output changed? Revert the changes with the keyboard shortcut cmd + z.
  • Change fruits[i] to fruits. Re-run the code - has the output changed? Revert the changes with the keyboard shortcut cmd + z.

If some questions arose out of doing this - you did it right! We will come back together and discuss this as a class.


Live Coding - Model

Code Challenge

Print out only the numbers from the following Array that are greater than 10:

numbers = [10, 11, 7, 19, 4, 52, 89, 9, 12, 10]


Common Misconceptions

  • An Array is not required when writing a for statement. You saw this demonstrated in the first part of class! Because Arrays are so commonly used in for statements, sometimes we forget it's possible.
  • for statements are not magically connected to Arrays; when code "loops through an Array" that is becuase the length of the Array is part of the condition, and the Array is (most likely) called in the code block.


Practice

Use a for statement to solve each problem. You can do this work in the place that works best for you - Dev Tools Console, a file in Atom, or an online editor.

Utilize a for statement to print out the numbers 3-14.


Find the square of each number:

numbers = [2, 4, 6, 8, 10, 12]


Print out each String, but capitalize the first character of each String:

words = ["sunny", "beach", "waves", "relax"]


Print out only names that begin with "P":

names = ["Pilar", "Petunia", "Pamela", "Tan", "Amanda", "Phil"]


Print out every odd number between 0 and 100. Do NOT print any even numbers, and do NOT create an Array to help you do this.


Check For Understanding

Follow the directions in the README of this GitHub repository, and submit your fork in the submission form.





Back