For(var prop in obj) Make me understand

var obj = {a:1, b:2, c:3};

for (var prop in obj) {
console.log(“obj.” + prop + " = " + obj[prop]);
// “obj.a = 1”
// “obj.b = 2”
// “obj.c = 3”

The variable prop is kind of special variable which represent value of obj?


The syntax lets you declare a variable which will be assigned the key of every property in an object, allowing you to iterate through all the keys in an object. In what you wrote, you’re declaring this variable with var prop so in each iteration a variable named prop will reference the current key in the object. You can name this variable anything.

The loop is useful because you can’t loop through the properties stored in an object like you can an array. Object.keys(obj) servers a similar purpose which will return an array of all the values stored in the object.

You can also compare to the for...of loop which is very similar but allows you to iterate through an array.

Hope that helps!

var obj = {a:1, b:2, c:3}; // note that objects have properties (a, b, c) and values (1, 2, 3) like in the given example

for (var prop in obj) { // "prop" is just a variable name. you can replace it with anything like anyVariableNameAndThisWillAlsoWork
	console.log(prop);  // here, we want to know what the variable "prop" contains and have it displayed in the console so we would understand how loop works
// a
// b
// c

// So, everytime the loop iterates, the variable "prop" contains the property of the object.
1 Like