The for...in
loop statement in JavaScript allows you to iterate over the properties of an object. It is used to loop through all enumerable properties inherited from the object’s prototype chain.
With for...in
, you can access each property name and its corresponding value within the loop. To exclude inherited properties and only iterate over an object’s own properties, you can use the hasOwnProperty()
method. Understanding the for...in
loop is crucial for effectively working with objects in JavaScript.
The syntax for the for...in
loop statement in JavaScript is as follows:
for (variable in object) {
// code to be executed
}
variable
: This is a variable that will hold the name of each property during each iteration. You can choose any valid variable name.object
: This is the object you want to iterate over. It can be any object, including arrays, built-in objects, or user-defined objects.
The for...in
loop is especially useful when you want to perform an operation on each property of an object dynamically.
JavaScript for in loop example
Simple example code that demonstrates the usage of the for...in
loop in JavaScript:
const car = {
brand: 'Toyota',
model: 'Camry',
year: 2021,
color: 'Blue'
};
for (let key in car) {
console.log(key + ': ' + car[key]);
}
Output:
Update Values of Properties
To update the values of properties within an object in JavaScript, you can use the for...in
loop in combination with the assignment.
const person = {
name: 'John',
age: 30,
profession: 'Developer'
};
for (let prop in person) {
if (person.hasOwnProperty(prop)) {
person[prop] = 'Updated';
}
}
console.log(person);
for…in with Strings
Iterate over the characters of a string.
const message = "Hello, World!";
for (let index in message) {
console.log(message[index]);
}
for…in with Arrays
Let’s iterate over the indices (keys) of an array.
const numbers = [1, 2, 3, 4, 5];
for (let index in numbers) {
console.log(numbers[index]);
}
Comment if you have any doubts or suggestions on this JS essential topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version