3. JS Loops

Kostas Diakogiannis
Curso por Kostas Diakogiannis, atualizado more than 1 year ago Colaboradores

Descrição

Introduction to JS loops. While and for.

Informações do módulo

Sem etiquetas

Contexto

Course's Objectives 1. To achieve repetitive tasks without having to type repetitive code through loops. 2. To understand the different types of loops that exist. 3. What is the difference between a while loop and a for loop and when is appropriate to use the one in favor of the other. 4. What kind of problems loop solve in general. 5. What is the purpose of the 'break' and 'continue' keyword? 6. Learn the use of nested loops. 7. Practice practice practice
Mostrar menos
Sem etiquetas

Contexto

Happy Birthday to every User   Imagine that you are having a social network web application with 100.000 users. These users have store their personal information to your application like their name, username, access password, hobbies, interests AND their date of birth. Imagine that you want to check everyday for every user, if it has it's birthday or not and if yes you want to give him a free premium account of your app for the next week. Although you might already know how to accomplish this task for a specific user it is going to be extremely hard to achieve for 100.000 users. That means that you need to write 100.000 conditions and from them, detect which ones have birthday on the give day in order to give them the premium account. That doesn't sound very efficient right?
Mostrar menos
Sem etiquetas

Contexto

Repeating tasks with loops   Loops is maybe the most useful and most fundamental concept of structured programming. If it wasn't for loops it would be impossible to achieve all the things that we have done till today, not only in the web industry but in programming in general.  Loops give us the opportunity to write and execute the same block of code repeatedly, as long as we specify. Let's take a look at our problem. We have 10 users that they have enrolled themselves to our application. Everyday i want to check if some of them, one of them or maybe all of them have birthday today. This is the condition i need to check. I need to compare if the date today matches the day that they have given us as a birthday. If this is true then i give the user the premium account for the week. If not, nothing happens.  Luckily by creating a loop we don't need to write these conditions 10 times. We create a loop that runs 10 times in this case and we check for the same condition once by changing the date of birth of every user for our comparison. Of course, in order for this example to work, we need to have a place where we store all the birthdays for every user (something like an JS Array), but that comes later.
Mostrar menos
Sem etiquetas

Fluxograma

A basic overview of loop flowchart!

Contexto

Loop execution flow   In the diagram above you can see the basic normal flow of a loop and how it executes. As you will find later, there are more than one types of loops, but all of them they work the same way.  At the beginning there is an initial state when the loop starts (for example we set a variable x = 1), then always we check if a condition evaluates to true (in this case the condition is x < 100), if this is true, then we execute some code we define. After the execution of the code, we may update the value of x to 2. Then we check the condition again ( x < 100 which is still true), execute the same code as before. We update and continue these steps until the condition that is specified evaluates to false, this causes our loop to break and exit. (stop being executed in other words).
Mostrar menos
Sem etiquetas

Contexto

The while loop   There are more than one ways to execute a repeated code. While loop is one of the commonest. The syntax can be found above in the picture, the first step is instantiating a variable and giving a specific value. Most of the times this is going to be a number but as we will see later in the course this is not mandatory (many times you will find out it can be boolean etc). Inside the while parenthesis follows a condition (that returns a boolean value always). While this condition is true, the code inside the following curly braces will be executed. Last but not least, we need to update the value of the "Counter" variable. This is very important in order to avoid loop infinity. Avoid creating a loop whose condition ALWAYS evaluate to true, and thus runs forever. Once the body of the loop is over, the value has been updated and then the condition is checked again in order to decide if we will execute the body of the loop once again or we will exit the loop! Already confused let's see a practical example!
Mostrar menos
Sem etiquetas

Contexto

L-1 Print all number's multiples up to 10 Write a program that accepts a number and prints to the console it's multiplication table, up to 10. For example the number 5 case,  should print to the console the following sequence of numbers: 5 10 15 20 25 30 35 40 45 50   The same for number 7: 7, 14, 21, 28, 35 ..... 70 etc.
Mostrar menos
Sem etiquetas

Contexto

L-2 Odd or Even exercise Fill the blanks to the code above in order to create a loop that goes from number 1 to 100 and for every number prints if it is an odd or an even number. Create the currentNumber variable and update it accordingly. Put this part of code inside a loop to achieve your goal. Estimated time: 10 mins.
Mostrar menos
Sem etiquetas

Contexto

L-3 The FizzBuzz Problem Without modifying the existing code you see, but only for changing the order and adding the necessary curly braces wherever needed, rewrite the solution to the famous FizzBuzz problem so it doesn't accept only one given number, but loops and does the same for all numbers (integers) from 1 to 100 (100 included!)
Mostrar menos
Sem etiquetas

Contexto

L-4 The container problem Suppose you own a ship. This is ship can carry up to 10.000 Kg in terms of weight. A merchant wants you to carry his goods with your ship. He has 500 containers and he wants you to carry as many as possible. All containers have an identifying number from 1 to 500. The first 100 containers weight 10Kg each. The containers with number from 101 up to 200 (included) weight 20kg each. The containers with number from 201 up to 250 (included) weight 50kg each. The containers with number from 251 up to 300 (included) weight 100kg each. The containers with number from 301 up to 400 (included) weight 200kg each. The rest weight 500 Kg each. Put as many containers as possible without sinking your ship. Find a way to stop adding weight if you surpass the limit your ship can afford. Print to the console exact how many containers you have included to your ship and how much is the difference between the total weight of the containers and the weight your ship can afford (free available weight).
Mostrar menos
Sem etiquetas

Contexto

The Break keyword The break keyword can exit the body loop whenever we specify. It is heavily used when we want to stop the loop process under a when condition is met, usually when an exception occurs. There is no specific syntax, we just throw the word 'break' inside the body of the loop context and if the code finds itself inside there, and reaches the 'break' line the loop exits! L-5. In the previous container problem. The captain is tremendously superstitious and will not accept the ship to travel if it contains more than 112 containers! Find a way to stop adding more containers when we reach the 112 containers and ship the shipment right away! You may want to apply what you have learned today.
Mostrar menos
Sem etiquetas

Contexto

The continue keyword The continue keyword is another reserved keyword that is used heavily in loops, exactly like break. Continue acts like 'skip' of this iteration part of the loop. Any time the interpreter finds  this word inside the body  loop automatically skips the part that is below and goes to the condition on top and executes the next step (or iteration) of the loop L-6. In the container example the containers with number between 150-159 were broken, so they should have not been included at the first place. Fix this by adding the continue statement to your current code.
Mostrar menos
Sem etiquetas

Contexto

The For loop The for loop is another type of loop exactly like while. In fact logic-wise the difference is non-existent. For is used exactly for the same purpose as while, the only thing that changes is the syntax as the image above shows. So instead of defining the decisive variable outside the loop, we do it inside the condition, by splitting the parenthesis section into three areas. Inside the first area we define the start of the decisive variable, at second position comes the condition we check after every iteration and last we define how we update the variable's value after iteration has finished. This may seems to be a little bit harder at the beginning but leaves the body of the loop cleaner to put only the repeated code there. Attention: For loops are a preferable option when we know exactly the number of iterations from before (thus is the best option when working with numbers).  It is a good practice to use while loop when we don't know exactly the number of iterations from before. Besides that, there is no significance difference between for and while and all the principles that we have learned in a while loop can also be applied in a for loop. (like the 'break' and 'continue' keyword).
Mostrar menos
Sem etiquetas

Contexto

L-7 Refactor the ship container problem Refactor the ship container problem in such a way that you have exactly the same result, but now you are going to use a for loop instead. Estimated time: 15 Minutes.
Mostrar menos
Sem etiquetas

Contexto

L-8 Pay the employees today! Imagine that you are currently the big boss of a company. It is the first day of the month and you want to pay your employees. In the company now work 72 employees. The cashier/balance of your company now is 100.000$. You will use these to pay the salaries to your workers. Analytically your company is comprised of: 50 workers with ops and general duites: each earns 1.000$. 10 web developers:       4 of them are Frontend Developers: each earns 1.500$       4 of them are Backend Developers: each earns 2.000$       2 of them are FullStack developers: each earns 3.000$ 5 Project managers: each earns 4.000$ 5 DevOps Engineers: each earns 5.000$ 2 Data Scientists:       1 Data Analyst: each earns $7.500       1 Machine Learning Engineer: each earns 10.000$   Suppose you want to start paying them one by one and pay as many as you can. But there is an order. Everyone has an identifying number. The Data Scientist come first (from 1 to 2). Then the web devs (3 to 4, Full stack come first), (5 to 8, here come the Backend Devs), then the frontend Devs. Then the normal workers. Then DevOps Engineers Project Managers last. Print a message to console after the program to know exactly how many people have not received their payment yet, in order to keep track on the amount of people who await for the salaries. Additionally print how much money has left to your balance after the payment. Estimated time: 30 Minutes.
Mostrar menos
Sem etiquetas
L-9 The clothing sales problem. Imagine that you work at sales department in a clothing-shop and you are responsible for selling 3 products: A t-shirt that costs 10$ A pair of Jeans that costs 30$ and a Jacket that costs 150$ You have noticed a paradox pattern. Every three customers, the new customer buy the same things. For example the first customer buys 3 t-shirts. The second customer buys a 2 Jeans. The third customer buys a jacket. And then again the same from the beginning. The fourth customer again 3 t-shirts. The fifth customer buys again 2 jeans. The sixth customer buys again one jacket. That continues until the end of the day. Find out how much money your cashier has if the initial cashier was already at 150$ and the total number of customers at the end of the day was 78.   Estimated Time:  30 Minutes.
Mostrar menos
Sem etiquetas

Contexto

Nested Loops Nested loops is also a possible feature. That means you can create a loop inside a loop. This is very useful when we want to make a repetitive task, and for each item of it we want to assign another repetitive task one more. For example what if we want to find all customers of our web app that are coming from Iran and they were born after 1988 (are under 30 years old), those are two different properties. First we need to find those that are coming from Iran, so we need to loop through ALL customers, and every time we find someone coming from Iran, we also loop through all the other properties to find it's birthdate and if it's before 1988. There are also other ways to solve this problem (such as object properties) but until then we will stick to this. Let's see a practical example.
Mostrar menos
Sem etiquetas
L-10 Create a matrix table multiplication exercise Create a script that shows all the multiplication tables from numbers from 1 to 10 (and all the results by multiplying each number with each number from 1 to 10). Example follows: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 2, 4, 6, 8, 10, 12, 14,16, 18, 20, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 etc. Estimated time: 20 Mins.
Mostrar menos
Sem etiquetas
L-11 Prime Numbers exercise Check all numbers from 1 to 100 and print to the console only the primes. p.s. Primes are the numbers that are perfectly divisible ONLY by themselves and 1! Estimated Time: 30 Minutes
Mostrar menos