DEV Community

Passionate Coder
Passionate Coder

Posted on

3 3

Use of for in loop

We have so many loops now in javascript to optimize our code and ignore using old for loop. One such case can be seen in below example.

We have given two array and asked to achieve an object like below

const keys = ["name", "city","gender", "job"];
const values = ["Test User", "Pune", "Female", "Developer"];

Desired Output
{
    name:"Test User"
    city:"Pune"
    gender:"female"
    job:"Developer"
}
Enter fullscreen mode Exit fullscreen mode

Using for loop:

const obj = {}
for(let i = 0; i<keys.length; i++){
     obj[keys[i]] = values[i]
}
Enter fullscreen mode Exit fullscreen mode

using for in loop:

const obj = {}
for(let i in keys) {
    obj[keys[i]] = values[i]
}
Enter fullscreen mode Exit fullscreen mode

using for in loop our code looks more clean and its less complex and more efficient

I hope it will help someone

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay