Loops/Higher Order Functions (Javascript)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

To start, let's convert a for loop into a while loop:

// A for loop that prints 1, 2, and 3 for (let counterOne = 1; counterOne < 4; counterOne++){ console.log(counterOne); } // A while loop that prints 1, 2, and 3 let counterTwo = 1; while (counterTwo < 4) { console.log(counterTwo); counterTwo++; }

for (let counter = 0; counter < 4; counter++) { console.log(counter); } What is the outcome?

0 1 2 3

do...while statement example

const firstMessage = 'I will print!'; const secondMessage = 'I will not print!'; // A do while with a stopping condition that evaluates to false do { console.log(firstMessage) } while (true === false); // A while loop with a stopping condition that evaluates to false while (true === false){ console.log(secondMessage) };

Another do...while example

const money = [1,2,3,2,2]; let i = 0; let list = 0; do{ list += money[i]; i++; }while(i < money.length) console.log(list) (Another One)

Example of the nested for loop

const myArray = [6, 19, 20,22]; const yourArray = [10,32,12,22]; let number = 0; let number2 = 0; for (let i = 0; i < myArray.length; i++) { for (let j = 0; j < yourArray.length; j++) { if (myArray[i] === yourArray[j]) { console.log('Both loops have the number: ' + yourArray[j]) } } }

Before we write our own loops let's take a moment to develop an appreciation for loops. The best way to do that is by showing you how...

cumbersome it would be if a repeated task required you to type out the same code every single time.

for loops are very handy for iterating over what?

data structures

Iterator variables can have any name, but it's best practice to use a what type of variable name?

descriptive variable name

In some cases, you want a piece of code to run at least once and then loop based on a specific condition after its initial run. What statement do we use?

do...while statement

Note that the while and do...while loop are different! Unlike the while loop...

do...while will run at least once whether or not the condition evaluates to true.

What does a for loop look like?

for (let counter = 0; counter < 4; counter++) { console.log(counter); }

Here's how we might tell the computer to "count to three":

for (let i = 1; i<=3; i++) { console.log(i) }

Example of break

for(let i = 0; i < 100; i++){ if(i == 59){ console.log("Orange") break } console.log("Coconut") }

Example of the for loop

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

Looping in Reverse example

for(var val = 9; val >= 0; val--){ console.log(val) }

Another example of functions as data

function playCheckFromTheBackStreet(arr){ for(let value of arr){ if(value = "chores"){ return "There is a chores on your list" } } } let know = playCheckFromTheBackStreet console.log(know(["qwert","popcorn","chores","knowledge"])) (Another One)

Another example of break

function test(arr){ for(let value of arr){ if(value >= 10){ console.log("Higher") } else { break } } console.log("Low") } let final = test([1,2,4,3]) final // Low (Another One)

Break statements can be especially helpful when we're looping through what?

large data structures!

Example of a Looping through Arrays

let animals = [1,2,3,4,5,6]; for(let i = 0; i < animals.length; i++){ let monkey = animals[i] * 2; console.log(monkey) }

Another example of looping through arrays

let arr = ["yokai","boomer","mario"] for(let value = 0; value < arr.length; value++){ console.log(arr[value]) } //yokai //boomer //mario (Another One)

for (let i = 0; i < 99; i++) { if (i > 2 ) { break; } console.log('Banana.'); } console.log('Orange you glad I broke out the loop!'); What is the output

Banana. Banana. Banana. Orange you glad I broke out the loop!

const announceThatIAmDoingImportantWork = () => { console.log("I'm doing very important work!"); }; const busy = announceThatIAmDoingImportantWork; busy(); What does this code do?

Busy is a variable that holds a reference to our original function. If we could look up the address in memory of busy and the address in memory of announceThatIAmDoingImportantWork they would point to the same place. Our new busy() function can be invoked with parentheses as if that was the name we originally gave our function. Notice how we assign: announceThatIAmDoingImportantWork without parentheses as the value to the busy variable. We want to assign the value of the function itself, not the value it returns when invoked.

Another example of functions as parameters

let arr = [20,30,100,50,400] function needForSpeed(ar){ return ar.map(x=>x * 3) } function check(value){ for(let val of value){ if(val > 80){ return "There is a number greater than 80 -> " + val } } } let test = needForSpeed(arr) let final = check(test) console.log(final) //There is a number greater than 80 -> 90 (Another example)

You'll hear the generic term iterate when referring to loops; What does iterate means?

To repeat

What are steps of the iterator variable in a for loop?

1. It is initialized 2. Checked against the stopping condition 3. Assigned a new value on each loop iteration

A for loop contains three expressions separated by semi colon(;) inside the parentheses:

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.

Nested loop

A loop running inside another loop

Loop

A programming tool that repeats a set of instructions until a specified condition, called a stopping condition is reached

We call the functions that get passed in as what?

Parameters and invoked callback functions because they get called during the execution of the higher-order function.

In JavaScript, functions are what type of functions?

First class objects. This means that, like other objects you've encountered, JavaScript functions can have properties and methods

What is the order of the do...while statement?

First, the code block after the do keyword is executed once. Then the condition is evaluated. If the condition evaluates to true, the block will execute again. The looping stops when the condition evaluates to false.

When we need to reuse a task in our code, we often bundle that action in a...

Function

A higher-order function is a function that either accepts what?

Functions as parameters, returns a function, or both!

const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion']; for (let i = 0; i < animals.length; i++){ console.log(animals[i]); } What is the output of this?

Grizzly Bear Sloth Sea Lion

We're also going to learn about another way to add a level of abstraction to our programming, what is it called?

Higher-order functions

What are higher order functions?

Higher-order functions are functions that accept other functions as arguments and/or return functions as output. This enables us to build abstractions on other abstractions, just like "We hosted a birthday party" is an abstraction that may build on the abstraction "We made a cake."

// A while loop that prints 1, 2, and 3 let counterTwo = 1; while (counterTwo < 4) { console.log(counterTwo); counterTwo++; } What would happen if we didn't increment counterTwo inside our block?

If we didn't include this, counterTwo would always have its initial value, 1. That would mean the testing condition counterTwo < 4 would always evaluate to true and our loop would never stop running!

const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion']; for (let i = 0; i < animals.length; i++){ console.log(animals[i]); } What does this example do?

In the loop above, we've named our iterator variable i. This is a variable naming convention you'll see in a lot of loops. When we use i to iterate through arrays we can think of it as being short-hand for the word index. Notice how our stopping condition checks that i is less than animals.length. 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. If we tried to access an element at the index of animals.length we will have gone too far!

let countString = ''; let i = 0; do { countString = countString + i; i++; } while (i < 5); console.log(countString); What does this example do?

In this example, the code block makes changes to the countString variable by appending the string form of the i variable to it.

timeFuncRuntime(() => { for (let i = 10; i>0; i--){ console.log(i); } }); What does this code do?

In this example, we invoked timeFuncRuntime() with an anonymous function that counts backwards from 10. Anonymous functions can be arguments too!

What's wrong with infinite loops?

Infinite loops can take up all of your computer's processing power potentially freezing your computer

When we speak to other humans, we share a vocabulary that gives us quick ways to communicate complicated concepts. When we say "bake", it calls to mind a familiar subroutine— preheating an oven, putting something into an oven for a set amount of time, and finally removing it. This allows us to abstract away a lot of the details and communicate key concepts more concisely. Instead of listing all those details, we can say, "We baked a cake," and still impart all that meaning to you. In programming, we can accomplish what?

It accomplish the "abstraction" by writing functions. In addition to allowing us to reuse our code, functions help to make clear, readable programs. If you encountered countToThree() in a program, you might be able to quickly guess what the function did without having to stop and read the function's body.

What does the break keyword allows?

It allows the programs to "break" out of the loop from within the loop's block.

What does the for loop include?

It includes an iterator variable that usually appears in all three expressions

// A while loop that prints 1, 2, and 3 let counterTwo = 1; while (counterTwo < 4) { console.log(counterTwo); counterTwo++; } Break this down.

Let's break down what's happening with our while loop syntax: The counterTwo variable is declared before the loop. We can access it inside our while loop since it's in the global scope. We start our loop with the keyword while followed by our stopping condition, or test condition. This will be evaluated before each round of the loop. While the condition evaluates to true, the block will continue to run. Once it evaluates to false the loop will stop. Next, we have our loop's code block which prints counterTwo to the console and increments counterTwo.

const myArray = [6, 19, 20]; const yourArray = [19, 81, 2]; for (let i = 0; i < myArray.length; i++) { for (let j = 0; j < yourArray.length; j++) { if (myArray[i] === yourArray[j]) { console.log('Both loops have the number: ' + yourArray[j]) } } }; What does this example do?

Let's think about what's happening in the nested loop in our example. For each element in the outer loop array, myArray, the inner loop will run in its entirety comparing the current element from the outer array, myArray[i], to each element in the inner array, yourArray[j]. When it finds a match, it prints a string to the console.

What does loops allow?

Loops allow us to create efficient code that automates processes to make scalable, manageable programs

When we pass a function in as an argument to another function do we invoke it?

No

What does the do...while statement say?

Says to do a task once and then keep doing it until a specified condition is no longer met.

Instead of writing out the same code over and over, what does loops allows use to do?

Tell computers to repeat a given block of code on its own.

With callbacks, we pass in the function itself by typing what?

The function name without the parentheses (that would evaluate to the result of calling the function)

How can we loop through an array?

To loop through each element in an array, a for loop should use the array's length property in its condition

What can for loops be used for in an array?

To perform the same operation on each element in an array

for (let counter = 0; counter < 4; counter++) { console.log(counter); } Break down the parts of the for loop?

The initialization is let counter = 0, so the loop will start counting at 0. The stopping condition is counter < 4, meaning the loop will run as long as the iterator variable, counter, is less than 4. The iteration statement is counter++. This means after each loop, the value of counter will increase by 1. For the first iteration counter will equal 0, for the second iteration counter will equal 1, and so on. The code block is inside of the curly braces, console.log(counter), will execute until the condition evaluates to false. The condition will be false when counter is greater than or equal to 4 — the point that the condition becomes false is sometimes called the stop condition.

For each round of the outer for loop what happens?

The inner for loop will run completely

When we want to stop a loop from continuing to execute even though the original stopping condition we wrote for our loop hasn't been met, what should we use?

The keyword break

When a condition is met in a loop, what will happen?

The loop stops and the computer moves on to the next part of the program

Since functions are a type of object, what do these properties have?

They have properties such as .length and .name and methods such as toString(). You can see more about the methods and properties of functions in the documentation

What is a loop that never stops running called?

This is called an infinite loop and it's something we always want to avoid.

What are some uses for a nested for loop?

To compare the elements of two arrays or to shorten an element of a list

What if we want the for loop to log 3, 2, 1, and then 0?

To run a backward for loop, we must: Set the iterator variable to the highest desired value in the initialization expression. Set the stopping condition for when the iterator variable is less than the desired amount. The iterator should decrease in intervals after each iteration.

Invoking the function would evaluate what?

To the return value of that function call

JavaScript functions behave like any other data type in the language; How does it behave?

We can assign functions to variables, and we can reassign them to new variables.

const announceThatIAmDoingImportantWork = () => { console.log("I'm doing very important work!"); }; How can we sacrifice this code without losing the main code.

We can re-assign the function to a variable with a suitably short name: const busy = announceThatIAmDoingImportantWork; busy(); // This function call barely takes any space!

const higherOrderFunc = param => { param(); return `I just invoked ${param.name} as a callback function!` } const anotherFunc = () => { return 'I\'m being invoked by the higher-order function!'; } higherOrderFunc(anotherFunc); What does this code do?

We wrote a higher-order function higherOrderFunc that accepts a single parameter, param. Inside the body, param gets invoked using parentheses. And finally, a string is returned, telling us the name of the callback function that was passed in. Below the higher-order function, we have another function aptly named anotherFunc. This function aspires to be called inside the higher-order function. Lastly, we invoke higherOrderFunc(), passing in anotherFunc as its argument, thus fulfilling its dreams of being called by the higher-order function.

When should we use a while loop?

When we do not know how many times we are going to loop

When do we write a loop?

When we see that a process has to repeat multiple times in a row

Can a higher-order function could be used with any callback function which makes it a potentially powerful piece of code?

Yes

Can functions be passed into parameters?

Yes

Can we loop through an array?

Yes

How to output the array in the loop?

You need to put the variable of the loop inside the brackets of the array, like this: array[element]

Loops iterate or repeat an action until what is met?

a specific condition is met.

Another example of a nested loop

let count = 0 const letterCheck = ["hello","goodbye","so far","see you later!"] for(let value = 0; value < letterCheck.length; value++){ for(let val = 0; val < letterCheck[value].length; val++){ if(letterCheck[value][val] === "e"){ count++ } } } console.log(count) //5 (Another one)

Example of the while loop

let money = 8; while(money > 0){ console.log(money); money--; }

Example of functions as parameters

let mr_bobby_sales = [30,40,50,20,10,30,20] let mr_max_sales = [39,38,29,49,10,10,39] const mr_bobby = (sales) =>{ let week_for_bobby = sales.reduce((x,y)=>x+y); return week_for_bobby; }; const mr_max = (sales) =>{ let number = 0; for(let i = 0; i < sales.length; i++){ number += sales[i]; } return number; } const total = (sale1,sale2) =>{ if(sale1 > sale2){ return `Mr Bobby has more sales by ${sale1-sale2}`; }else if(sale1 < sale2){ return `Mr Max has more sales by ${sale2-sale1}` } else{ return `They both make the same amount ${sale1}` } } const bobby = mr_bobby(mr_bobby_sales) const max = mr_max(mr_max_sales) console.log(total(bobby,max))

Functions as data example

let numbers = [3,4,5,6,7,2,4,5,2,3,5,3,2,5,2] const numbersthatIcancountbutIdonotwant = work =>{ let number = 0; for(let i = 0;i<numbers.length;i++){ number += numbers[i] } return number } const word = numbersthatIcancountbutIdonotwant; console.log(word(numbers))

Another example of a while loop

let valueCheck = ["popeye","the","sailor","man"] let count = valueCheck.length while(count > 0){ console.log(valueCheck[count - 1]) count-- } //man //sailor //the //popeye (Another example)

Another example of a for loop

let word = "yokai" for(let value = 0; value < word.length; value++){ console.log(value) } //0 //1 //2 //3 //4 (Another One)

Another example of looping in reverse

let word = "yokai" for(let value = word.length; value >= 0; value--){ console.log(value) } //5 //4 //3 //2 //1 //0 (Another One)

With breaks, we can add _________ besides the stopping condition, and exit _________ when they're met.

test conditions, the loop


Set pelajaran terkait

Chapter 17 Iggy Practice Questions, Chapter 18 Iggy Practice Questions 3-2, IGGY Ch.37 Care of Patients with Shock - Textbook, Chapter 19 Iggy Practice questions, Care of Patients with Problems with HIV Disease Ch 19 (Elsevier), IGGY Ch.19 - Care of...

View Set

Participles and Participial Phrases Circle the participial phrase and draw parentheses around the noun or pronoun it modifies

View Set

Entornos económicos que enfrentan los negocios CAP 4

View Set

Circulatory/Cardiovascular system test questions

View Set

Chapter 23: Management of Patients with Coronary Vascular Disorders

View Set

College Microeconomics Course Chapter 12

View Set

Operations Instructional Area Exam (9%)

View Set

Chapter 6- FL Statutes, Rules, & Regulations Common to All Lines

View Set

Completing The Application, Underwriting, And Delivering The Policy

View Set

Rel 101 Web Midterm (Chinese Religions) Bos

View Set

Comptia Network Plus and Security Plus

View Set