Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is shorter notation for this in latest JavaScript?

I've got this:

const id = speakerRec.id;
const firstName = speakerRec.firstName;
const lastName = speakerRec.lastName;

and I think there is something like this but can't remember it.

const [id, firstName, lastName] = speakerRec;
like image 781
Pete Avatar asked May 24 '26 23:05

Pete


2 Answers

You need to use {} for destructuring object properties:

const {id, firstName, lastName} = speakerRec;

[] is used for array destructuring:

const [one, two, three] = [1, 2, 3];

Demonstration:

const speakerRec = {
  id: "mySpeaker",
  firstName: "Jack",
  lastName: "Bashford"
};

const { id, firstName, lastName } = speakerRec;

console.log(id);
console.log(firstName);
console.log(lastName);

const [one, two, three] = [1, 2, 3];

console.log(one);
console.log(two);
console.log(three);
like image 60
Jack Bashford Avatar answered May 26 '26 12:05

Jack Bashford


It's an object, so use object destructuring (not array destructuring):

const { id, firstName, lastName } = speakerRec;
like image 40
CertainPerformance Avatar answered May 26 '26 13:05

CertainPerformance