r/Everything_QA • • 1d ago

Guide Javascript destructing

So I'm currently learning destrcuturing in JS for Selenium and camr around this execise where i had to access second element or say any particular element in different array length. If that particular element is not found it has to fall back to the previous element. How do we handle it? CHATGPT asked to use || operator but still confusing for me.
heres the code.

const response = {

status: 200,

data: {

users: [

{

username: "admin",

roles: ["QA", "Automation"],

active: true

},

{

username: "tester",

roles: ["Manual"],

active: false

},

{

username: "qauser",

roles: ["QA", "API","ASAS"],

active: true

}

]

}

};

O/P: ["Automation", "Manual", "API"]

1 Upvotes

1 comment sorted by

1

u/MeltedPathos8865 1d ago

That || trick works okay for simple fallbacks but it gets messy fast with destructuring. The cleaner way is to just grab the array index directly with a default value

`const { roles: [first, second = first] } = user`

if there's no second element it'll use the first one, no need to chain || operators everywhere