Search code examples
javascriptobjectjavascript-objectsfor-in-loopobject-properties

Why we cant use normal for loop to print javascript object?


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.


Solution

  • 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]);
    }