Skip to content

Instantly share code, notes, and snippets.

@ilearnjavascript
Created March 28, 2019 23:49
Show Gist options
  • Save ilearnjavascript/ac094130d4e1da4ec632fb50d692eca6 to your computer and use it in GitHub Desktop.
Save ilearnjavascript/ac094130d4e1da4ec632fb50d692eca6 to your computer and use it in GitHub Desktop.
Enahnced Object Literals
/* --- No repetition if key: value is identical --- */
// ES5
var es5_getLaptopProperties = function(make, model, year) {
return {
make: make,
model: model,
year: year
}
}
es5_getLaptopProperties("Apple", "MacBook", "2015");
// outputs: {make: "Apple", model: "MacBook", year: "2015"}
// ES6
const es6_getLaptopProperties = (make, model, year) => {
return {
make,
model,
year
}
}
es6_getLaptopProperties("Apple", "MacBook", "2015");
// outputs: {make: "Apple", model: "MacBook", year: "2015"}
/* --- Shorter methodnames --- */
// ES5
var es5_getLaptopMethods = function (make, model, year) {
return {
sayModel: function () {
return model;
}
}
}
es5_getLaptopMethods("Apple", "MacBook", "2015");
// outputs: {sayModel: ƒ}
// ES6
const es6_getLaptopMethods = (make, model, year) => {
return {
sayModel() {
return model;
}
// in object methods the ':function()' is now optional
}
}
es6_getLaptopMethods("Apple", "MacBook", "2015");
// outputs: {sayModel: ƒ}
/* --- Use variables as keys --- */
// ES5
var es5_changeLaptopProperties = function (make, model, year) {
var key1 = 'make';
var obj = {
model: model,
year: year
}
obj[key1] = make;
return obj;
}
es5_changeLaptopProperties("Apple", "MacBook", "2015");
// outputs: {model: "MacBook", year: "2015", make: "Apple"}
// ES6
const es6_changeLaptopProperties = (make, model, year) => {
var key1 = 'make';
var obj = {
[key1]: make,
model,
year
}
return obj;
}
es6_changeLaptopProperties("Apple", "MacBook", "2015");
const key = "make";
let i = 0;
const laptop = {
[key + ++i]: "Apple",
[key + ++i]: "Dell",
[key + ++i]: "HP"
}
// also see that dynamic keys are possible
console.log(laptop.make1); //"Apple"
console.log(laptop.make2); //"Dell"
console.log(laptop.make3); //"HP"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment