Hello! Welcome to our next lesson.
In our last session, we mastered how to iterate over an object's properties using both the classic for...in loop and the modern Object.keys() method. This gave you the tools to programmatically access and work with data inside an existing object.
Today, we'll shift our focus from reading object data to writing it more effectively. We'll explore some modern JavaScript (ES6) features that make creating objects cleaner and more concise. The learning outcome for this lesson is to use ES6 shorthand for defining properties and methods in object literals.
While this might seem like a small topic, it's incredibly important. This syntax is used everywhere in modern JavaScript, especially in the Next.js and TypeScript ecosystems you're aiming for. Mastering it will make your code more professional and easier to read.
The Old Way: Repetitive Object Creation
Before ES6, creating objects from existing variables could feel a bit repetitive. Imagine you have variables and you want to create a user object from them:
const username = 'code_explorer';
const email = 'explorer@example.com';
// Pre-ES6 way
const user = {
username: username,
email: email
};
console.log(user); // { username: 'code_explorer', email: 'explorer@example.com' }
Notice the repetition: username: username and email: email. The property name is identical to the variable name. The same applies to defining methods (functions on objects):
// Pre-ES6 way
const user = {
username: 'code_explorer',
greet: function() {
console.log('Hello, ' + this.username);
}
};
user.greet(); // Hello, code_explorer
Here, we have to explicitly write greet: function(). ES6 provides elegant shortcuts for both of these situations.
Property Shorthand: Don't Repeat Yourself
ES6 introduced property value shorthand. The rule is simple: if you are creating an object property whose name is the same as the name of the variable holding its value, you can just type the name once.
Let's see that first example again, but with the shorthand:
const username = 'code_explorer';
const email = 'explorer@example.com';
// ES6 Property Shorthand
const user = {
username,
email
};
console.log(user); // { username: 'code_explorer', email: 'explorer@example.com' }
Isn't that much cleaner? JavaScript sees the variable username inside the object literal {} and understands you want to create a property named "username" with the value from the username variable.
This is extremely common in functions that construct objects:
// A function that creates a user object
function createUser(name, age) {
// Before ES6, you would return { name: name, age: age };
return { name, age }; // Much cleaner with shorthand!
}
const newUser = createUser('Alice', 30);
console.log(newUser); // { name: 'Alice', age: 30 }
Method Shorthand: Cleaner Functions on Objects
Similarly, ES6 provides a method shorthand that lets you define a function on an object without the function keyword or the colon :.
Here is the greet example with method shorthand:
// ES6 Method Shorthand
const user = {
username: 'code_explorer',
greet() {
console.log('Hello, ' + this.username);
}
};
user.greet(); // Hello, code_explorer
This syntax makes the object's method look much neater and more intentional.
To see both of these shorthands in action, watch the following short video.
JavaScript ES6 Tutorial #8 - Object Literal Enhancements
The video 'JavaScript ES6 Tutorial #8 - Object Literal Enhancements' from Net Ninja provides a quick and clear demonstration of both property and method shorthands.
Watch from 01:36 to 04:13. The first part (until 02:25) covers property shorthand, and the second part covers method shorthand. Notice how the code is simplified in each case.
A "Deep Dive" on Method Shorthand and this
You have a preference for understanding the "why," so here's a crucial detail. The method shorthand greet() { ... } creates a regular function, not an arrow function. This is important because it means the this keyword inside it behaves as we learned in a previous lesson: it refers to the object the method was called on (in this case, user).
This is a common point of confusion. If you were to use an arrow function for a method, this would not work as you expect, because arrow functions don't have their own this context.
For a great explanation and code example of this exact issue, check out the following resource.
Modern JS Syntax (ES6+) - 33 JavaScript Concepts
The article 'Modern JS Syntax (ES6+)' has a section that directly addresses why arrow functions are a poor choice for object methods. This reinforces our understanding of this.
Navigate to the 'Test Your Knowledge' section and read the answer to 'Question 4: Why shouldn't you use arrow functions as object methods?'. Pay close attention to the code comparison.
Test your understanding!
Refactor the following code to use ES6 property and method shorthands.
const title = 'The Stand';
const author = 'Stephen King';
const pages = 1153;
const book = {
title: title,
author: author,
pageCount: pages, // Note: property name is different from variable name
getInfo: function() {
return `${this.title} by ${this.author} has ${this.pageCount} pages.`;
}
};
console.log(book.getInfo());
Show answer
Here's the refactored code:
const title = 'The Stand';
const author = 'Stephen King';
const pages = 1153;
const book = {
// Shorthand for title and author
title,
author,
// pageCount must be defined normally as the variable name 'pages' is different
pageCount: pages,
// Method shorthand for getInfo
getInfo() {
return `${this.title} by ${this.author} has ${this.pageCount} pages.`;
}
};
console.log(book.getInfo()); // "The Stand by Stephen King has 1153 pages."
Explanation:
titleandauthorcan use property shorthand because the variable names match the desired property names.pageCount: pagescannot be shortened because the property key (pageCount) is different from the variable name (pages).getInfo()uses method shorthand, removing the colon andfunctionkeyword.
Computed Property Names: Dynamic Keys
What if you need to set a property key on an object based on the value of a variable? Before ES6, you had to create the object first and then add the property using bracket notation.
let propertyKey = 'os_version';
let computer = {
brand: 'Apple',
model: 'MacBook Pro'
};
// Add the property after creation
computer[propertyKey] = 'Sonoma';
console.log(computer); // { brand: 'Apple', model: 'MacBook Pro', os_version: 'Sonoma' }
ES6 introduced computed property names, which let you use an expression in square brackets [] directly inside the object literal to define a property key dynamically.
let propertyKey = 'os_version';
const computer = {
brand: 'Apple',
model: 'MacBook Pro',
[propertyKey]: 'Sonoma' // The expression in [] is evaluated and used as the key
};
console.log(computer); // { brand: 'Apple', model: 'MacBook Pro', os_version: 'Sonoma' }
The expression inside the brackets is evaluated, and its result becomes the property key. This is a powerful feature for creating objects with dynamic structures.
To explore this concept in more detail, please read the following section from a highly respected JavaScript resource.
The article 'Objects' from javascript.info provides an excellent explanation of computed properties with clear, practical examples.
In this article, find and read the section titled 'Computed properties'. It starts right after the initial examples of bracket notation. Focus on how square brackets are used within an object literal to create a property from a variable.
Conclusion
Today, you've added three powerful ES6 syntaxes to your toolkit for working with objects. These shorthands are not just about typing less; they're about writing code that is more expressive and readable, which is a crucial skill for any developer.
Key Takeaways:
- Property Shorthand: Use
{ name }instead of{ name: name }when a variable and property key have the same name. - Method Shorthand: Define object methods with
myMethod() { ... }instead ofmyMethod: function() { ... }for cleaner code. Remember, this creates a regular function wherethisworks as expected. - Computed Properties: Use
[myVariable]: valueinside an object literal to set property keys dynamically from a variable or expression.
Next Up
This lesson concludes our module on JavaScript objects! You now know how to create them, add properties and methods, understand this, iterate over them, and use modern syntax to do it all concisely.
In the next module, we will move on to another fundamental data structure in JavaScript: Arrays. You'll learn how to create and manage ordered lists of data, which, along with objects, form the backbone of almost any application you will build. We will start by learning how to create arrays and access or modify their elements by index.