Web Design

JavaScript Loops

Code:

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Loops</title>
  </head>
  <body>
    <h1>JavaScript Loop</h1>
    <h2>General Loops</h2>
    <ul>
      <li>for</li>
      <li>while</li>
      <li>do...while</li>
    </ul>
    <h2>Array Specific iterations</h2>
    <script src="app.js"></script>
  </body>
</html>

JavaScript

// Loops
// General Loop

// for

// i = i + 1;
for (let i = 0; i <= 10; i++) {
  console.log(i);
}

// while

const cars = ["Tesla", "Audi", "BMW", "Ford"];

let m = 0;

while (m < cars.length) {
  console.log(cars[m]);
  m++;
}

// do...while

let n = 0;

do {
  console.log("car " + cars[n]);
  n++;
} while (n < cars.length);

// forEach

cars.forEach(function (car, index, array) {
  //   console.log(car);
  //   console.log(`${index} : ${car}`);
  console.log(array);
});

// Map

const carBrands = [
  { id: 1, brandName: "Tesla" },
  { id: 2, brandName: "Sckoda" },
  { id: 3, brandName: "Toyota" },
];

const ids = carBrands.map((brandName) => {
  return brandName.id;
});

console.log(ids);

// for...in

const user = {
  firstName: "Norbert",
  lastName: "Menyhart",
  age: 35,
};

for (let u in user) {
  // key
  //   console.log(u);
  //   Value
  //   console.log(user[u]);
  console.log(`${u} : ${user[u]}`);
}

// for...of

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

for (let car of cars) {
  console.log("for of " + car);
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: