JavaScript for in loop

In JavaScript, for…in loop is similar to for loop to iterate over an objects or array elements. The loop allows you to perform an action on each property of an object or element of an array.

Syntax of the Javascript For In Loop

for(va…


This content originally appeared on DEV Community and was authored by Max

In JavaScript, for...in loop is similar to for loop to iterate over an objects or array elements. The loop allows you to perform an action on each property of an object or element of an array.

Syntax of the Javascript For In Loop

for(var property in object)  
{  
    // code to be executed  
}

Here, property is a string variable representing the property key, and object is the object to be iterated over.

Iterating Over an Object Example

const numbers = {
    "one": 1,
    "two": 2,
    "three": 3,
    "four": 4,
    "five": 5
}

for (let num in numbers) {
  console.log(`${num}: ${numbers[num]}`);
}

Output:

one: 1
two: 2
three: 3
four: 4
five: 5

Iterating Over an Array Example

const numbers = [1, 2, 3, 4, 5]; 
for (let index in numbers) {
    console.log(`Index: ${index} Value: ${numbers[index]}`); 
}

Output:

Index: 0 Value: 1
Index: 1 Value: 2
Index: 2 Value: 3
Index: 3 Value: 4
Index: 4 Value: 5

Learn Javascript Tutorial


This content originally appeared on DEV Community and was authored by Max


Print Share Comment Cite Upload Translate Updates
APA

Max | Sciencx (2023-04-22T14:09:46+00:00) JavaScript for in loop. Retrieved from https://www.scien.cx/2023/04/22/javascript-for-in-loop/

MLA
" » JavaScript for in loop." Max | Sciencx - Saturday April 22, 2023, https://www.scien.cx/2023/04/22/javascript-for-in-loop/
HARVARD
Max | Sciencx Saturday April 22, 2023 » JavaScript for in loop., viewed ,<https://www.scien.cx/2023/04/22/javascript-for-in-loop/>
VANCOUVER
Max | Sciencx - » JavaScript for in loop. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/04/22/javascript-for-in-loop/
CHICAGO
" » JavaScript for in loop." Max | Sciencx - Accessed . https://www.scien.cx/2023/04/22/javascript-for-in-loop/
IEEE
" » JavaScript for in loop." Max | Sciencx [Online]. Available: https://www.scien.cx/2023/04/22/javascript-for-in-loop/. [Accessed: ]
rf:citation
» JavaScript for in loop | Max | Sciencx | https://www.scien.cx/2023/04/22/javascript-for-in-loop/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.