Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
Object destructuring in Javascript - trying to make sense

probably a bit of a silly question but I'm only a beginner and there's something I am trying to understand properly.

When we have code like this:

const { userName } = await getUserProfile({ userId });

What exactly is happening here? Are we destructuring userName out of the getUserProfile object to be able to access that property? And does userId mean that the getUserProfile function has a parameter that is an object that has a property userId?

Sorry, if this is too beginner of a question but would really appreciate it if anyone had the time to explain this to me please.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I'd say the function does something like this:

interface Options {
   userId: number;
}

interface ReturnItem {
  userName: string;
}

const getUserProfile = async (options: Options): Promise<ReturnItem> => {
  // make some request with the id
  const response = await axios.get(`/look/up/my/user/${options.userId}`);
  return response.data;
}

The destructuring is based off of the types defined in the function, so instead of getting an object back, you're just pulling the item out of the returned object as the types define that's what you can expect to receive.

Instead of doing the following:

const myId = 1;
const myResult = await getUserProfile({userId: myId});
console.log(myResult.userName);

you can do:

const userId = 1;
const {userName} = await getUserProfile({userId});
console.log(userName);

Another example:

const myReturnData = {
  userName: 'Bjork'
};

userName can now be accessed in the following ways:

console.log(myReturnData.userName);

or

const {userName} = myReturnData;
console.log(userName);

Destructuring is taking those values in your object and assigning them to variables.

A bit further..

const myReturnData = {
  userName: 'Bjork',
  coolnessFactor: 10000
};

const {userName, coolnessFactor} = myReturnData;
console.log('My User is: ', userName);
console.log('and my Coolnessfactor is: ', coolnessFactor);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!