본문 바로가기
Udemy - The web developer camp

JavaScript Loop

by Hanachoi 2022. 9. 13.

# For loop

  • The whole point of looping is repeating some functionality. ex) print 'hello' 10times / sum all numbers in an array. 
  • There are multiple types of loops : for / while /for...of/for...in 
for(
	[initialExpression];
    [condition];
    [incrementExpression];
)


for(let i = 1; i<=10; i++){  // start at 1 / stop at 10 / add 1 each time
	console.log(i);
}
  • Condition part should be always true while this loop is working and increment expression should change value about variable. 

#For loop example

  • If you want to print just even numbers, add 2 for increment expression
for(let i=0; i<=20; i+=2){
	console.log(i)
} // you just get even numbers until condition part is right
  • if you want to print just odd numbers 
for(let i = 1; i<=20; i+=2){
	console.log(i)
}
  • if you want decrease 10  from 100 to 0 
for(let i = 100; i>=0; i-=10){
    console.log(i);
}

 

#Infinite Loops

  • If condition expression is never gonna be false, then the loop will be working forever. It makes your browser got stopped. Loop can be runned a thousand times but you don't want infinite loop which is never going to stop. It will barrel through all of your computer's memory.

 

#Looping over arrays

  • We use loop when we interact arrays. we also call it iterating over an array, doing something with or for each element in an array. 
  • To loop over an array, start at index 0 and continue looping to unitl last index (length -1)
  • The pattern in this example is really common when it comes to looping over arrays and at least that will iterate over every well every index.
const animals = ['lions','tigers','bears'];

for(let i=0; i<animals.length; i++){
	console.log(i,animals[i]);
}

//0 'lions'
//1 'tigers'
//2 'bears'
  • you can also write coditonal part like this. for(let i = 0; i <= animals.length-1; i++) which is our greatest index. 
  • Let's go the other direction.
  • We need to start with the highest index which is [animals.length-1]
for(let i = animals.length-1; i>=0 ; i--){ //인덱스는 0부터 시작하니까 길이는 항상 +1이 된다. 거기서 부터 시작해서 마지막 index인 0까지 오는게 포인트
	console.log(animals[i])
}

 

 

#Nested Loop

  • The idea here is literally putting a for loop inside the body of another for loop.
  • In practice, what this means is that for every single iteration of the outer loop, and the inner loop is going to have its own full cycle. 
for(let i=1; i<=10; i++){
	console.log(`i is: ${i}`)
    for(let j =1; j<4; j++){
    	console.log(`      j is:${j}`)
    }
}
  • Outer loop runs then times, so i is going to be one and then it will be two and then three and so on. But while i is one, we have this entire nested loop which runs for j starting at one up to but not including four. So this outer loop works 10 tiems and inner one works 3times 10 times 3 = 30 times work 
  • We also have nested arrays and we can use nested loop well .If you want to print all arrays, you can code like it below
const seatingChart = [
	['kristin','Eric', 'Namita'],
    ['Geoffrey','Justina','Antonio','Kevin'],
    ['Yuma','Sakura','Jack','Erika']
]

for(let i=0; i<seatingChart.length;i++){
	console.log(seatingChart[i])
}
  • But if you want to print all individual's name, you need more loop. What you need to do is now loop over seating chart of i seating chart of i.
const seatingChart = [
	['kristin','Eric', 'Namita'],
    ['Geoffrey','Justina','Antonio','Kevin'],
    ['Yuma','Sakura','Jack','Erika']
]

for(let i=0; i<seatingChart.length;i++){
	const row = seatingChart[i];
    console.log(`row ${i+1}`) //row가 1부터 시작해야해서 1을 더함
    for(let j= 0; j< row.length; j++){
    	console.log(row[j])
    }
}

 

 

#While loops

  • While loops continue running as long as the test condition is true. If condition is evaluated as falut, the loop is done. 
let num = 0;
while(num<10){
	console.log(num);
    num++;
}
  • If you don't write num++ part, it will be infinite loop easily cuz If just condition is num<10, it will be always true. 
  • If you put num++ part ahead of [console.log(num);], the result will be different. Because numbers will be added before it is played. 
  • when we have arrays,whatever the length of that array is,  we are always going to iterate and times if the array is twenty times or thousand items. 
  • while loop is more useful when we have something that is truly variable, we may not know how many times iterates and that could involve user inputs. like chase game and password matching 
const SECRET = 'BabyHippo';

let guess = prompt('enter the secret code');

while(guess!==SECRET){	
	guess= prompt('enter the secret code...'); // this code happen over and over until you get it exactly right
}
console.log('Congrats You got the secret!!')
  • While the condition in parenthese is true, guess code is going to happen over and over. If you got the secret code(SECRET and guess is matched), console.log out of while loop will be out. 

 

#The break keyword

  • For while loop , we often use break keyword. it is used in another loop as well but it is rare.
  • If the condition is true and we break out that is going to stop the execution of the loop immediately as soon as brake is encountered. And then code just resumes running after our loop. 
let input = prompt('Hey say something!');
while(true){
	input = prompt(input);
    if(input === 'Stop copying me'){
    	break;
    }
}
console.log('okay you win')
  • If while condition is true and we don't have break, it keeps repeating. you can escpae the infinite loop with break keyword. 

# Making number guessing game

let maximum = parseInt(prompt('Enter the maximum number!'));

while(!maximum){
  maximum = parseInt(prompt('Enter the maximum number!'));
}

// Math.floor(Math.random()*10) +1 ; // this is going to give us one to ten 

const targetNum = Math.floor(Math.random()*maximum) +1 ;
console.log(targetNum);

let guess = parseInt(prompt('enter your first guess!')); // the number will be string, so you need to change it into number with parseInt keyword.
let attempts = 1; 

while(parseInt(guess) !== targetNum){
    if(guess === 'q') break;
    attempts++; // if you are in this loop, which means your are still trying to get the number
    if(guess > targetNum){
      guess= prompt('Too high! Enter a new guess!')
    }else{
      guess= prompt('Too low! Enter a new guess!')
    }
}
if(guess ==='q'){
    console.log('okay you quit')
}else{
console.log(`You got it! It took you ${attempts} guesses`);
}

 

 

#For...of

const subreddits = ['cringe','books','chicken','funny','pics','soccor']

for(let i =0 ; i <subreddits.legnth; i++){
	console.log(`Vist reddit.com/r/${subreddits[i]}`)
} 

// Vist reddit.com/r/cringe
//Vist reddit.com/r/books ...
  • In this example, you can reach out each element in this array. But we also have another way to get the same result as this but shoter code
for(let subreddit of subreddits){
	console.log(`Vist reddit.com/r/${subreddit}`);
}
  • When you need to iterate array, this for..of keyword is more useful. You don't need to card about index in this array. If you need to access index, it might be better to use just for loop.
for(variable of iterable){
	statement
}
  • When you have two nested for loop, this syntax will be better to use a for loop. 
for(let row of seatingChart){
	for(student of row){
   		console.log(student); 
   }
}
  • This code is easier to read because it is written as a variable that corresponds to the individual element, not a variable that corresponds to an index or just the number that than I have to plug in to the array. 
  • This loop is a nice and easy way of iterating over arrays (or other iterable objects) even can be used with strings.
for(let word of "hello world"){
	console.log(word)
}
  • Each character is iterable over this loop.

 

#Object loop

  • If you have an object that is made up of key-value element pairs, it is not iterable object. 
  • In this case, you can use for...in loop. It is going to iterate over an object. It is just give us the key in the object.
const testScores = {
	keenan : 80;
    damo : 67;
    kim: 89;
    shawn:91;
    marlon: 72;
   	nadia:83;
    elvira:97;
}

for(let person in testScores){
	console.log(`${person} scored ${testScores[person]}`);
}
  • If you want value instead of key, use squre brackets like an example.
  • There is another way to get key and values.
Object.keys(testScores) //[ keenan, damon, kim ....]
Object.values(testScores) // [80, 67, 89 ...]
Object.entries(testScores) // it will give us nested arrays key-value pairs.
  • If you want to get average of all of these values, you can use Object.values(testScores) But unfortunately, object doesn't have length. So you can get all the values in this array and I can just take the length of this. 
let total = 0;

for(let score of Object.values(testScores)){
	total+=score; // each time through, it will be added 
}
 //
let total = 0;
let scores = Object.values(testScores);
for(let score of scores){
	total+=score;
}

console.log(total/scores.length)

'Udemy - The web developer camp' 카테고리의 다른 글

JavaScript function level up  (0) 2022.10.13
JavaScript Function  (0) 2022.09.28
JavaScript Object Literals  (0) 2022.09.09
JavaScript Arrays  (0) 2022.08.23
Javascript Making decisions  (0) 2022.08.06

댓글