Object Literals
Object literal syntax is just a way to make our code look nicer. To show how to use this, we will just look at the old/uglier way of doing things, and then see the ES6/prettier way of doing things.
There are three major ways object literals do this.
- Provides a shorthand syntax for initializing properties from variables.
- Enables the ability to have computed property names in an object literal definition.
- Provides a shorthand syntax for defining function methods.
This:
const red = '#ff0000';
const blue = '#0000ff';
const COLORS = { red: red, blue: blue };
can now be:
const red = '#ff0000';
const blue = '#0000ff';
const colors = { red, blue };
The old way:
const fields = ['firstName', 'lastName', 'phoneNumber'];
const props = { fields: fields };
Can now be:
const fields = ['firstName', 'lastName', 'phoneNumber'];
const props = { fields };
The old way:
const canvasDimensions = function(width, initialHeight) {
const height = initialHeight * 9 / 16;
return {
width: width,
height: height
};
}
Can now be:
const canvasDimensions = (width, initialHeight) => {
const height = initialHeight * 9 / 16;
return {
width,
height
};
}
Methods
Methods in an object no longer need to have the function
keyword. To facilitate this, we drop the :
too.
This:
const color = 'red';
const car = {
color: color,
drive: function() {
return 'Vroom!';
},
getColor: function() {
return this.color;
}
};
Can now be:
const color = 'red';
const car = {
color,
drive() {
return 'Vroom!';
},
getColor() {
return this.color;
}
};