ES6/ES2015 For Newbies Lesson 3: Enhanced Object Literals and Default Values

Share:
Source Code

Enhanced Object Literals

Objects are essential part of Javascript. It’s no surprise that they’re getting a feature lift in ES6:


// Enhanved Object Literals
let foo = 'bar';
let myObj = {
	foo,	// same as foo: foo
	_name: 'pentacode',
	_age: 5,
	whoAmI() {
		// Set a function property 
		console.log(`I am ${this._name} and I am ${this._age} years old`);
	},
	[ 'prop_' + (() => 'dynamic')() ]: 'a dynamic property'	// Dynamic key name
}

console.log(myObj.foo);
console.log(myObj.whoAmI())
console.log(myObj.prop_dynamic)

Short hand

If the key of the object is the same as the value, you can write it in the short hand way, so instead of

let foo = 'bar';

let myObj = {
    foo: foo
};

you can do:

let foo = 'bar';

let myObj = {
    foo
};

Dynamic properties

You can define a function and make references to values previously defined in the object by using this.var_name:

let myObj = {
_name: 'pentacode',
_age: 5,
whoAmI() {
// Set a function property 
console.log(`I am ${this._name} and I am ${this._age} years old`);
	}
}

You can also define a computed value as property name:

// Enhanved Object Literals
let myObj = {
	[ 'prop_' + (() => 'dynamic')() ]: 'a dynamic property'	// Dynamic key name
}

if you wrap the property name in [ ] , you can make the property dynamic.

Default Values

Does this look familiar?

function add(x,y) {
	if (!y) {
		y = 0;
	}
	console.log(x + y);
	return x + y;
}

it’s a common practice to always check if an argument exists before doing anything with it, and in many cases, set it to equal to a default value.

ES6 allows us to make this simpler by letting us define default values right on the parameter:

function add(x, y=0) {
	console.log(x + y);
	return x + y;
}

add(3, 4); // 7
add(3); // 3

and here’s an example of evaluating default value at call time:

// Evaluating default value at call time
function pusher(value, arr = []) {
	arr.push(value);
	return arr;
}

let fruit = pusher('apple');
console.log(fruit);	// ['apple']

Default values make your code easy to read and write by eliminating the dusty old value check boilerplate we used to write and let us focus on what we need to do instead.

[frames playlist=’3′]

Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode