Skip to content

Latest commit

 

History

History

11 - Enhanced Object Literals

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Section 11: Enhanced Object Literals

Enhanced Object Literals

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);


[Exercise] Multiple Properties with Enhanced Notation

Question

Refactor to use enhanced literal notation.

const red = '#ff0000';
const blue = '#0000ff';

const COLORS = { red: red, blue: blue };

Solution

const red = '#ff0000';
const blue = '#0000ff';

const COLORS = { red, blue };


[Exercise] Condensing Code with Enhanced Literals

Question

Refactor the following to use enhance object literal syntax.

const fields = ['firstName', 'lastName', 'phoneNumber'];
const props = { fields: fields };

Solution

const fields = ['firstName', 'lastName', 'phoneNumber'];
const props = { fields };


[Exercise] Literals in Functions

Question

Refactor to use enhanced literal notation.

const canvasDimensions = function(width, initialHeight) {
  const height = initialHeight * 9 /16;
  return {
    width: width,
    height: height
  };
}

Solution

const canvasDimensions = function(width, initialHeight) {
  const height = initialHeight * 9 /16;
  return { width, height };
}


[Exercise] Refactor to Use Enhanced Literal Notation

Question

Refactor to use enhanced literal notation.

const color = 'red';

const Car = {
  color: color,
  drive() {
    return 'Vroom!';
  },
  getColor() {
    return this.color;
  }
};

Solution

const color = 'red';

const Car = {
  color,
  drive() { return 'Vroom!' },
  getColor() { return this.color }
};