JavaScript #19 ~ Loop

HJ's Coding Journey·2021년 7월 21일
0

[Learn] JavaScript

목록 보기
20/20

Introduction

A loop is one of the most essential control method used in JavaScript. We use loops to specifically automate repetitive tasks that are performed again and again. Without loops, we would have to write repetitive codes in various lines which creates an inefficient cycle. With loops, however, we can create an automated functionality within a few lines of codes.

As mentioned, without loops we would have to write every single single line of repetitive code until the end:

// W/o loops
console.log('repetition 1');
console.log('repetition 2');
console.log('repetition 3');
console.log('repetition 4');
console.log('repetition 5');
console.log('repetition 6');
console.log('repetition 7');
console.log('repetition 8');
console.log('repetition 9');
console.log('repetition 10');

Using loops, we can make this process easier. Most frequently, we would be using a for loop. Within the for loop, we start by declaring a counter which marks the beginning position of the count. Then, we set the position in which we want to end our counter. Lastly, we set the way in which we want to count our specific counter (ex. +, -, *, /). Overall, the for loop will keep running while the condition is true.

for (let rep = 1; rep <= 10; rep++) {
  console.log(`repetition ${rep}`);
}  

Looping Arrays

Once we know how to use loops in JavaScript, we can apply this method into arrays and objects. Looping through an array is one of the most common practices in JavaScript.

First and foremost, we use loops to get and read data stored within arrays.

// Reading data within an array using for loops.
const profile = {
  'John',
  'Smith',
  2037 - 1991,
  'developer',
  ['Michael', 'Peter', 'Steven']
};
for (let i = 0; i < profile.length; i++) {
  console.log(profile[i]);
}

Additionally, we can use pre-existing arrays to create a new array entirely.

const types = [];
for (let i = 0; i < profile.length; i++) {
  types.push(typeof profile[i]); // [string, string, number, string, object]
  // -OR- types[i] = typeof profile[i];
}

Continue & Break

Continue is a method that is used to exit the current iteration of the loop and move on to the next iteration (skips iteration depending on the condition).

// --Continue-- (code exits an iteration depending on the condition)
console.log("--- ONLY STRINGS ---");
for (let i = 0; i < profile.length; i++) {
  if (typeof profile[i] !== "string") continue;
  console.log(profile[i]);
}

Break is a method used to completely terminate the entire loop at a certain point (the loop ends after breaking the loop).

// --Break-- (code terminates as soon as the condition is true)
console.log("--- BREAK WITH NUMBER ---");
for (let i = 0; i < profile.length; i++) {
  if (typeof profile[i] === "number") break;
  console.log(profile[i]);
}

Looping Backwards

Just as we use loops to read data in order, we can also loop data in the reverse order. The rule is similar and we just need to start from the end all the way to the start.

const john = [
  'John',
  'Smith',
  2037 - 1991,
  'developer',
  ['Michael', 'Peter', 'Steven']
];
for (let i = john.length - 1; i >= 0; i--) {
  console.log(john[i]); // array order in reverse index order
}

Loops in Loops

For various purposes, we can create loops inside another loop. This process often occur with things that need to run a cycle of different tasks. A good example is a cycle of exercise routine we perform in the gym. There are certain amount of repetition in each exercise that must be performed to complete the routine.

for (let exercise = 1; exercise <= 3; exercise++) {
  console.log(`-------- Starting exercise ${exercise}`);
  for (let rep = 1; rep <= 5; rep++) {
    console.log(`Lifting weight repetition ${rep}`);
  }
}
/// Results
-------- Starting exercise 1
Exercise 1: Lifting weight repetition 1
Exercise 1: Lifting weight repetition 2
Exercise 1: Lifting weight repetition 3
Exercise 1: Lifting weight repetition 4
Exercise 1: Lifting weight repetition 5
-------- Starting exercise 2
Exercise 2: Lifting weight repetition 1
Exercise 2: Lifting weight repetition 2
Exercise 2: Lifting weight repetition 3
Exercise 2: Lifting weight repetition 4
Exercise 2: Lifting weight repetition 5
-------- Starting exercise 3
Exercise 3: Lifting weight repetition 1
Exercise 3: Lifting weight repetition 2
Exercise 3: Lifting weight repetition 3
Exercise 3: Lifting weight repetition 4
Exercise 3: Lifting weight repetition 5

While Loop

The while loop works exactly like the for loop in looping data. However, while loop does not necessarily require a counter in order to loop over data types. Because of this, the while loop has more freedom to loop data in almost any condition.

// --for loop-- reference
for (let rep = 1; rep <= 10; rep++) {
  console.log(`Lifting weights repetition ${rep}`);
// --while loop--
let rep = 1;
while (rep <= 10) {
  console.log(`Lifting weights repetition ${rep}`);
  rep++;

For example, rolling a dice and getting random numbers does not require a set number. We simply obtain the number given through the dice. For making this happen, we would most likely use a 'while loop' rather than a 'for loop' that requires a counter.

// Example that does not need a counter like the 'for loop'
// Ex) Rolling a dice until we get a 6 (we don't know how many times the loop needs to run)
let dice = Math.trunc(Math.random() * 6) + 1;
//
while (dice !== 6) {
  console.log(`You rolled a ${dice}`);
  dice = Math.trunc(Math.random() * 6) + 1;
  if (dice === 6) {
    console.log("Loop is about to end...");
  }
}
profile
Improving Everyday

0개의 댓글