- Enhanced Object Literals
- [Exercise] Multiple Properties with Enhanced Notation
- [Exercise] Condensing Code with Enhanced Literals
- [Exercise] Literals in Functions
- [Exercise] Refactor to Use Enhanced Literal Notation
With the Enhanced Object Literals feature, we can make object handling even easier in all modern browsers. Let's see the example below.
// without Enhanced Object Literals
function createBookShop(inventory) {
return {
inventory: inventory,
inventoryValue: function() {
return this.inventory.reduce((total, book) => total + book.price, 0);
},
priceForTitle: function(title) {
return this.inventory.find(book => book.title === title).price;
}
};
}
// with Enhanced Object Literals
function createBookShop(inventory) {
return {
inventory,
inventoryValue() {
return this.inventory.reduce((total, book) => total + book.price, 0);
},
priceForTitle(title) {
return this.inventory.find(book => book.title === title).price;
}
};
}
const inventory = [
{ title: 'Harry Potter', price: 10 },
{ title: 'Eloquent JavaScript', price: 15 }
];
const bookShop = createBookShop(inventory);
Refactor to use enhanced literal notation.
const red = '#ff0000';
const blue = '#0000ff';
const COLORS = { red: red, blue: blue };
const red = '#ff0000';
const blue = '#0000ff';
const COLORS = { red, blue };
Refactor the following to use enhance object literal syntax.
const fields = ['firstName', 'lastName', 'phoneNumber'];
const props = { fields: fields };
const fields = ['firstName', 'lastName', 'phoneNumber'];
const props = { fields };
Refactor to use enhanced literal notation.
const canvasDimensions = function(width, initialHeight) {
const height = initialHeight * 9 /16;
return {
width: width,
height: height
};
}
const canvasDimensions = function(width, initialHeight) {
const height = initialHeight * 9 /16;
return { width, height };
}
Refactor to use enhanced literal notation.
const color = 'red';
const Car = {
color: color,
drive() {
return 'Vroom!';
},
getColor() {
return this.color;
}
};
const color = 'red';
const Car = {
color,
drive() { return 'Vroom!' },
getColor() { return this.color }
};