0

I am learning JavaScript, so today I came across to know that to print or get object properties the for..in loop is used. but i got confuse here because I haven't seen the for..in loop before. so I encountered a query that why we cant use for loop in JavaScript to print the object property? and how does this for..in loop works? here's an example.

let object1 = {
name : 'someone',
name2 : 'someone2',
phno : 234568969
};

and to print this everyone suggests

for(let key in object1)
{
console.log(key + "=" + object1[key]);
}

and my question is how does this loop works, and why this loop for printing the properties.

GeekyNerd
  • 7
  • 3
  • 2
    The for-in loop iterates over all [enumerable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Enumerable_attribute) of an object, and if a check for `hasOwnProperty` is not there, then it will iterate over the parent object's properties too – Kunal Mukherjee Jul 15 '20 at 16:36

2 Answers2

1

As opposed to for... of, the for... in loop will iterate over the enumerable properties (not their values) of an object.

In your example above, you're iterating over the keys of the object (the "properties labels"), and then using them to access the values on object1.

The example below will demonstrate more clearly how the for... in loop works.

const arr = [23, 45, 67, 56];

for(let index in arr) {
  // Note that only the indexes of the array are 
  // assigned to 'index', not the values
  console.log('Index:', index);
  
  // To access the values, you should do:
  console.log('Value:', arr[index])
}

And the same happens to objects:

const obj = {
  prop1: 'val 1',
  prop2: 2,
  prop3: { nestedObjProp: 'Nested Object Value' }
}

for(let key in obj) {
  console.log('Key:', key, '  Value:', obj[key]);
}

Refer to for... in on MDN web docs for more on for... in loops.

sandmann
  • 188
  • 11
1

Why we can't use for loop(Normal) in JavaScript to print the object property?
Ans. Because an object is a key-value pair, not an array.

How does this for..in loop works?
Ans. Loops through the properties of an object. (which can be used to get the value like object[property]).

Note: Property means key.

if you want to iterate through an array you can use simple for loop also like shown below.

var x = [1, 2, 3];

var i;
for (i = 0; i < x.length; i++) {
  console.log(x[i]);
}