For in Loop JavaScript Code Example
Last Updated On
Friday 19th Nov 2021
for in
loop iterates through all the properties of a particular object.
- It is Special loop beacuse you can pair it up with array.
for (let variable in obj) {
// do some stuff here
}
- It will loop through the properties of an array just like it did with the properties of an object.
- The
for-in
loops provide us the most straightforward way to loop over object keys and values.
Example 1
let Captains = {
"England": "Harry Kane",
"Italy": "Giorgio Chiellini",
"Germany": "Manuel Neuer"
}
for (let name in Captains) {
console.log(name, ':', Captains[name]);
}
- In this Example , the for in loop tends to iterate the object.
- With Each Iteration it returns the key and uses the key to access the specific value of that key that is object Captains.
// England : Harry Kane
// Italy : Giorgio Chiellini
// Germany : Manuel Neuer
Example 2
let books = ["Fist of the North Star", "Tokyo Ghoul", "Berserk"]
for (let book in books) {
console.log(book, ":", books[book]);
}
// 0 : Fist of the North Star
// 1 : Tokyo Ghoul
// 2 : Berserk
Example 3
let a = [];
let array = ['a', 'b', 'c', 'd'];
for (let index in array) {
a += array[index];
}
console.log(a) // abcd
- When using with arrays, the order of is independent of implementation.
- You Cannot access the values of the array in order that you except.