| by Kenneth Chase | No comments

Shorthand Property and Method Names in JavaScript ES6 | ES2015

In this video, we’re going to cover two features
of ES6. They are short hand properties and method
names. So really the whole point of both of these
new features is to make objects more concise. Now, it is syntactical sugar so it’s not really
necessary, but, it is nice. So let’s go ahead and cover it. Here, we have a formatMessage function which
is going to take in a name, an id, as well as an avatar. You’ll notice that all we’re doing it we’re
returning an object with each of those arguments as a property name on the object as well as
a timestamp. With the first feature we’ll be covering,
which is ES6’s shorthand property names, what we can do is you’ll notice here that we have
three properties whose keys are the exact same as their values, name, id, and avatar. So when that’s the case, what you can actually
do is we can come here and just delete the keys. So we get rid of name, we can get rid of id,
and we can get rid of avatar. So again, if the key, or the property name
is the exact same as the value, you can actually just go ahead and omit the key itself. So that will turn something that looks like
this, into an object that looks like this. Now, what if one of these properties was a
function? A function that is a property of an object
is called a method. So let’s say we also had a method here called
save which is just going to save the actual message. You’ll notice here that when we add a method
to an object, what we do is we have a property and we set that equal to a function expression,
as we’re doing right here. With ES6’s shorthand method names, what we
can do is we actually omit the function keyword itself. So now, code that used to look like this,
can now look like this. So again, both of these features are just
making objects more concise. So objects that used to look like this, can
now, look like this.

Leave a Reply