I am just confused in how the forin loop in js is used and why do we use const keyword in it

38 views Asked by At

I have a object named user where one of the properties is skills and im trying to find a user who have the maximum no. of skills.

let maximum = 0;
let name;
for (const user in users) {
    const len = users[user].skills.length;
    if (len > maximum) {
        maximum = len;
        name = user;
    }
    console.log(maximum, user);
}
console.log(maximum, name);
OUTPUT:
3 'Alex'
8 'Asab'
8 'Brook'
8 'Daniel'
8 'John'
8 'Thomas'
8 'Paul'
8 'Asab'

My doubt is why do we use const keyword beside user in the third line. I have tried using this loop without specifying any data type the output is:

let maximum = 0;
let name;
for(user in users){
    const len = users[user].skills.length;
    if(len > maximum) {
        maximum = len;
        name = user;
    }
    console.log(maximum,user);
}
console.log(maximum,user);
OUTPUT:
3 'Alex'
8 'Asab'
8 'Brook'
8 'Daniel'
8 'John'
8 'Thomas'
8 'Paul'
8 'Paul'

when i don't use any data type i don't know why but it is changing the name variable on its own.

1

There are 1 answers

0
Quentin On

My doubt is why do we use const keyword beside user in the third line.

Implicit globals have problems, so its a very bad idea to not use any declaration keyword.

The value of user never changes (note that its a new user each time you go around the loop, not a reassignment to the existing one), so it is natural to declare it as a const.