javascriptnotesControl Flow and Loops

Loops

// iterate over an array
var pageNames = [
  "Home",
  "About Us",
  "Contact Us",
  "JavaScript Playground",
  "News",
  "Blog",
];

Using keys (for…in)

for (var p in pageNames) {
  console.log(p, pageNames[p]);
}

Using values directly (for…of)

for (var v of pageNames) {
  console.log(v);
}
 
// for...of uses an object-specific iterator and loops over the values generated by that, so it can also be used as follows on objects
 
let obj = { a: 1, b: 2, c: 3 };
 
for (let [key, value] of Object.entries(obj)) {
  console.log(`Key: ${key}, Value: ${value}`);
}
 
// and maps
let myMap = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3],
]);
 
// Using for...of to iterate over key-value pairs
for (let [key, value] of myMap) {
  console.log(`Key: ${key}, Value: ${value}`);
}

Switch statements

The switch statement is used to execute one block of code among many based on the value of an expression. It is an alternative to using multiple if...else if statements. The switch statement evaluates an expression, matches the expression’s value to a case label, and executes the associated block of code. If no case matches, the default block is executed.

switch (expression) {
  case value1:
    // code to be executed if expression === value1
    break;
  case value2:
    // code to be executed if expression === value2
    break;
  default:
  // code to be executed if no case matches
}