Bjork
Bjork

Reputation: 57

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.

Upvotes: 0

Views: 64

Answers (1)

Petrogad
Petrogad

Reputation: 4423

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);

Upvotes: 1

Related Questions