본문 바로가기
TIL: Today I Learned

[TIL] 20201202 Repeating Stuff with Loops

by 김알리 2020. 12. 2.

Loops

  • Allows to repeat code
  • There are multiple types
    • for loop
    • while loop
    • for ... of loop
    • for ... in loop

 

 

for Loop

Syntax

for ([initialExpression]; [condition]; [incrementExpression]){
    //code
}

 

Example

for (let i=1; i<=10; i++){
    console.log(i);
} //1 2 3 4 5 6 7 8 9 10

 

 

 

Infinite Loops

  • Does not stop
  • Make sure the loop stops when it should.

 

 

 

Looping Over Arrays

//Examples

const animal = ['lions', 'tigers', 'bears'];
for (let i=0; i<animal.length; i++){
    console.log(i, animal[i]);
}

//1 lions 
//2 tigers
//3 bears

 

 

 

Nested Loop

Having another loop inside of a loop

 

 

 

while Loop

  • Continues running as long as the test condition is true.
  • Useful when it's unclear how many times this loop should run.
  • Syntax
while(test condition) {
    //code
}

 

 

Break Keyword

Breaks out of the loop immediately as soon as break is encountered.

 

 

 

for ... of Loop

  • Easier way of iterating over arrays & other iterable objects (i.e. string, map, set, object...)
  • Syntax
for ([variable] of [iterable]) {
    //code
}
  • Example
const numbers = {1, 2, 3, 4, 5};

for (let num of numbers) {
   console.log(num);
}

//1 2 3 4 5

 

 

Iterating Over Objects

  • Object Literals can't be iterated with for ... of
  • There are several ways to iterate over objects.

 

for ... in

  • Iterates only the keys
  • Syntax
for ([variable] in [object]){
    //code
}

 

Object.keys( )

  • Gives an array of keys
  • Syntax
Object.keys([object]);

 

Object.values( )

  • Gives an array of values
  • Syntax
Object.values([object]);

 

Object.entries( )

  • Gives an nested array of keys and values
  • Syntax
Object.entries([object]);

 

 

 

 

 

 

* This post is a summary of Udemy Course "The Web Developer Bootcamp" by Colt Steele.