//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; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter