Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Advanced JavaScript

You're reading from   Advanced JavaScript Speed up web development with the powerful features and benefits of JavaScript

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher
ISBN-13 9781789800104
Length 330 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Zachary Shute Zachary Shute
Author Profile Icon Zachary Shute
Zachary Shute
Arrow right icon
View More author details
Toc

Enhanced Object Properties


ECMAScript 6 added several enhancements to object literals as part of the ES6 syntactic sugar. ES6 added three ways to simplify the creation of object literals. These simplifications include a more concise syntax for initializing object properties from variables, a more concise syntax for defining function methods, and computed object property names.

Note

Syntactic sugar is a syntax that is designed to make expressions easier to read and express. It makes the syntax "sweeter" because code can be expressed concisely.

Object Properties

The shorthand for initializing object properties allows you to make more concise objects. In ES5, we needed to define the object properties with a key name and a value, as shown in the following code:

function getPersionES5( name, age, height ) {
  return {
    name: name,
    age: age,
    height: height
  };
}
getPersionES5( 'Zachary', 23, 195 )
// Expected output: { name: 'Zachary', age: 23, height: 195 }

Snippet 1.30: ES5 object properties

Notice the repetition in the object literal returned by the function. We name the property in the object after variable name causing duplication (<code>name: name</code>). In ES6, we can shorthand each property and remove the repetition. In ES6, we can simply state the variable in the object literal declaration and it will create a property with a key that matches the variable name and a value that matches the variable value. This is shown in the following code:

function getPersionES6( name, age, height ) {
  return {
    name,
    age,
    height
  };
}
getPersionES6( 'Zachary', 23, 195 )
// Expected output: { name: 'Zachary', age: 23, height: 195 }

Snippet 1.31: ES6 object properties

As you can see, both the ES5 and ES6 examples output the exact same object. However, in a large object literal declaration, we can save a lot of space and repetition by using this new shorthand.

Function Declarations

ES6 also added a shorthand for declaring function methods inside objects. In ES5, we had to state the property name, then define it as a function. This is shown in the following example:

function getPersonES5( name, age, height ) {
  return {
    name: name,
    height: height,

    getAge: function(){ return age; }
  };
}
getPersonES5( 'Zachary', 23, 195 ).getAge()
// Expected output: 23

Snippet 1.32: ES5 function properties

In ES6, we can define a function but with much less work. As with the property declaration, we don't need a key and value pair to create the function. The function name becomes the key name. This is shown in the following code:

function getPersionES6( name, age, height ) {
  return {
    name,
    height,

    getAge(){ return age; }
  };
}
getPersionES6( 'Zachary', 23, 195 ).getAge()
// Expected output: 23

Snippet 1.33: ES6 function properties

Notice the difference in the function declaration. We omit the function keyword and the colon after the property key name. Once again, this saves us a bit of space and simplifies things a little.

Computed Properties

ES6 also added a new, efficient way to create property names from variables. This is through computed property notation. As we already know, in ES5, there is only one way to create a dynamic property whose name is specified by a variable; this is through bracket notation, that is, : obj[ expression ] = 'value' . In ES6, we can use this same type of notation during the object literal's declaration. This is shown in the following example:

const varName = 'firstName';
const person = {
  [ varName ] = 'John',
  lastName: 'Smith'
};
console.log( person.firstName ); // Expected output: John

Snippet 1.34: ES6 Computed property

As we can see from the preceding snippet, the property name of varName was computed to be firstName. When accessing the property, we simply reference it as person.firstName. When creating computed properties in object literals, the value that's computed in the brackets does not need to be a variable; it can be almost any expression, even a function. An example of this is shown in the following code:

const varName = 'first';
function computeNameType( type ) {
  return type + 'Name';
}

const person = {
  [ varName + 'Name' ] = 'John',
  [ computeNameType( 'last' ) ]: 'Smith'
};

console.log( person.firstName ); // Expected output: John
console.log( person.lastName ); // Expected output: Smith

Snippet 1.35: Computed property from function

In the example shown in the preceding snippet, we created two variables. The first contains the string first and the second contains a function that returns a string. We then created an object and used computed property notation to create dynamic object key names. The first key name is equal to firstName. When person.firstName is accessed, the value that was saved will be returned. The second key name is equal to lastName. When person.lastName is accessed, the value that was saved will be returned.

In summary, ES6 added three ways to simplify the declaration of object literals, that is, property notation, function notation, and computed properties. To simplify property creation in objects, when properties are created from variables, we can omit the key name and the colon. The name property that's created is set to the variable name and the value is set to the value of the variable. To add a function as a property to an object, we can omit the colon and function keyword. The name of the property that's created is set to the function name and the value of the property is the function itself. Finally, we can create property names from computed expressions during the declaration of the object literal. We simply replace the key name with the expression in brackets. These three simplifications can save us space in our code and make object literal creation easier to read.

Exercise 7: Implementing Enhanced Object Properties

You are building a simple JavaScript math package to publish to Node Package Manager (NPM). Your module will export an object that contains several constants and functions. Using ES6 syntax, create the export object with the following functions and values: the value of pi, the ratio to convert inches to feet, a function that sums two arguments, and a function that subtracts two arguments. Log the object after it has been created.

To create objects using ES6 enhanced object properties and demonstrate the simplified syntax, perform the following steps:

  1. Create an object and save it into the exportObject variable.

  2. Create a variable called PI that contains the value of pi (3.1415).

  3. Create a variable called INCHES_TO_FEET and save the value of the inches to feet conversion ratio (0.083333).

    Using ES6 enhanced property notation, add a property called PI from the variable PI. Add a property called INCHES_TO_FEET from the INCHES_TO_FEET variable, which contains the inches to feet conversion ratio.

    Add a function property called sum that takes in two input arguments and returns the sum of the two input arguments.

    Add a function property called subtract that takes in two input arguments and returns the subtraction of the two input arguments.

  4. Log the object exportObject.

Code

index.js:
const PI = 3.1415;
const INCHES_TO_FEET = 0.083333;
const exportObject = {
 PI,
 INCHES_TO_FEET,
 sum( n1, n2 ) {
   return n1 + n2;
 },
 subtract( n1, n2 ) {
   return n1 - n2;
 }
};
console.log( exportObject );

Snippet 1.36: Enhanced object properties

Outcome

Figure 1.9: Enhanced object properties output

You have successfully created objects using ES6 enhanced object properties.

In this section, we showed you enhanced object properties, a syntactic sugar to help condense object property creation into fewer characters. We covered the shorthand for initializing object properties from variables and functions, and we covered the advanced features of computed object properties, that is, a way to create an object property name from a computed value, inline, while defining the object.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image