Loop - "for in"

PHOTO EMBED

Mon Apr 11 2022 20:52:10 GMT+0000 (Coordinated Universal Time)

Saved by @Luduwanda #javascriptreact

//The JS "for in" statement loops through the properties of an Object:

//Syntax
for (key in object){
  //code block to be executed
}

const person = {first_name: "John", last_name: "Doe", age:25};

let text = "";
for (let x in person) {
  text += person[x]
}

//John Doe 25

// Example explained
-   The for in loop iterates over a person object
-   Each iteration returns a key (x)
-   The key is used to access the value of the key
-   The value of the key is person[x]

//For in over arrays
for (variable in array){
  code
}

const numbers = [45,4,9]

let txt = "";
for (let x in numbers){
  txt += numbers[x]
}

// 45
//  4
//  9

//NOTE: It is better to use a "for" loop, a "for of" loop, or "Array.forEach()" when the order matters


///Array.forEach()
//forEach() method calls a function (a callback function) once for each array element
const numbers = [45,4,9]

let txt = "" (or let arr = []);
numbers.forEach(myFunction);

function myFunction(value, index, array){
  txt += value;
}
content_copyCOPY