Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Less code is better. In this video we review the Object Property Shorthand and how it reduces your keystrokes.
-
0:00
[SOUND] There's a saying that the best code is no code at all.
-
0:07
Which is to say the more code we write, the more likely we are to introduce a bug.
-
0:12
The more code browsers need to download, and
-
0:14
the longer it can take to review your own in your colleague's program.
-
0:18
In other words, writing less code is often a good thing.
-
0:22
One short ES2015 gives us is the object property shorthand.
-
0:26
It's a simple, but very useful addition to JavaScript.
-
0:30
Let's see it in action.
-
0:32
You can follow along using the latest workspace by opening the workspace for
-
0:35
this video.
-
0:36
Suppose I have a form that allows students to submit feedback about a course.
-
0:41
The form has three fields, name, comments and rating.
-
0:45
Over in shorthand.js, I have a submit function
-
0:49
that will compose the data object that eventually gets sent to the server.
-
0:55
The function also logs the keys of data and the values passed in this four loop.
-
1:01
And you might have noticed that the object
-
1:03
assigned to the data variable looks a bit different.
-
1:06
There aren't any keys.
-
1:08
Well, ES 2015 provides a shorter syntax for defining property keys and objects.
-
1:14
When the interpreter encounters a variable assignment without a property key,
-
1:19
the variable name itself is used as the property key.
-
1:23
So I'll call the submit function and pass it some values.
-
1:28
For name, let's type English.
-
1:32
And for comments, let's pass great course.
-
1:39
When I run this file in the console, you can see that the key names match
-
1:44
the variable names we passed to the object definition.
-
1:51
And you're not limited to string values as we used here.
-
1:56
It's also possible to use this new feature with booleans, numbers, objects,
-
2:00
arrays and classes.
-
2:02
So, for instance, if I set the rating to nine.
-
2:08
The console returns a rating of nine.
-
2:12
As you learned, property shorthand is easy to use, reduces keystrokes, and
-
2:16
potentially reduces bugs in your code.
-
2:19
In the next video, I'll go over the new for of syntax.
You need to sign up for Treehouse in order to download course files.
Sign up