code

JavaScript EC6 Object Features

Use Destructuring Assignment to Extract Values from Objects

Destructuring assignment is special syntax introduced in ES6, for neatly assigning values taken directly from an object.

const user = { name: 'John Doe', age: 34 };

const name = user.name;
const age = user.age;

// VS

const { name, age } = user;

So, it’s kinda turned around.

Again, name would have a value of the string John Doe, and age would have the number 34.

Here, the name and age variables will be created and assigned the values of their respective values from the user object. You can see how much cleaner this is.

You can extract as many or few values from the object as you want.

New variable names.

const { name: userName, age: userAge } = user;

You may read it as “get the value of user.name and assign it to a new variable named userName” and so on. The value of userName would be the string John Doe, and the value of userAge would be the number 34.

Use Destructuring Assignment to Assign Variables from Nested ObjectsPassed

You can use the same principles from the previous two lessons to destructure values from nested objects.

Using an object similar to previous examples:

const user = {
  johnDoe: { 
    age: 34,
    email: 'johnDoe@freeCodeCamp.com'
  }
};

Here’s how to extract the values of object properties and assign them to variables with the same name:

const { johnDoe: { age, email }} = user;

And here’s how you can assign an object properties’ values to variables with different names:

const { johnDoe: { age: userAge, email: userEmail }} = user;

Use Destructuring Assignment to Assign Variables from Arrays

const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c);
// outputs 1, 2 6

Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements

const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b);
console.log(arr);

// outputs

The console would display the values 1, 2 and [3, 4, 5, 7].

Use Destructuring Assignment to Pass an Object as a Function’s Parameters

const profileUpdate = (profileData) => {
  const { name, age, nationality, location } = profileData;

}

const profileUpdate = ({ name, age, nationality, location }) => {

}

Write Concise Object Literal Declarations Using Object Property Shorthand

// Old Way:

const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

// New Way:

const getMousePosition = (x, y) => ({ x, y });

Write Concise Declarative Functions with ES6

// Old Way:

const person = {
  name: "Taylor",
  sayHello: function() {
    return `Hello! My name is ${this.name}.`;
  }
};

// New Way:

const person = {
  name: "Taylor",
  sayHello() {
    return `Hello! My name is ${this.name}.`;
  }
};

Use class Syntax to Define a Constructor Function

// Old Way:

var SpaceShuttle = function(targetPlanet){
  this.targetPlanet = targetPlanet;
}
var zeus = new SpaceShuttle('Jupiter');

// New Way:

class SpaceShuttle {
  constructor(targetPlanet) {
    this.targetPlanet = targetPlanet;
  }
}
const zeus = new SpaceShuttle('Jupiter');

Use getters and setters to Control Access to an Object

You can obtain values from an object and set the value of a property within an object.

These are classically called getters and setters.

Getter functions are meant to simply return (get) the value of an object’s private variable to the user without the user directly accessing the private variable.

Setter functions are meant to modify (set) the value of an object’s private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.

class Book {
  constructor(author) {
    this._author = author;
  }
  // getter
  get writer() {
    return this._author;
  }
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
  }
}
const novel = new Book('anonymous');
console.log(novel.writer);
novel.writer = 'newAuthor';
console.log(novel.writer);

Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.