Object Enhancements in ES6

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

Building on the ES6 Shorthand Properties lesson, John shows the other new Object Enhancements in ES6 that will help you write less code and easily create complex Objects.

[00:00] ES6 comes with some object enhancements. If I want to create a car with that color and speed, I can just say "color, speed" and then log out car.color and car.speed. When I run this, you can see I get red and 10.

[00:18] That's because if you declare a property with the exact same name as something, it'll treat it just as if you did "color:color" and "speed:speed." This is the ES5 way, and this is the ES6 way.

[00:32] This even works for functions. If I create a function called "go" and say "vroom," I can simply add another property here, call it "go," and then say, "car.go." Then I'll run this. You can see it says, "vroom."

[00:50] Another cool thing...I'm going to format this just a little bit, put these on new lines...is that instead of using the function keyword, I can actually cut and paste this here. Then I'll just delete that.

[01:04] This is valid syntax for declaring a function on an object. If I save and run again, you'll see I get the same result. This is the ES6 way, and that's the ES5 way. It's basically a shorthand that saves you some typing.

[01:22] The last fun trick to show you is that if you type something like this, you can actually have a computed property where it'll evaluate this. This is pretty much just like if you were to do car["go"] like that, but now you're doing it inline inside of an object declaration.

[01:43] This will still work when I run it. I ran it and got vroom still. I can actually extract this go. I'll cut that out, say "var drive," paste it in there. Then we can put drive in here, hit save, run it. We still get vroom.

[02:01] You could do any sort of string concatenation or evaluation in there to generate some sort of string, which would evaluate into the name of something that you could then call later on.

Albert Yu
Albert Yu
~ 9 years ago

what is the color scheme?

Anna
Anna
~ 5 years ago

i like how your narration is so calm and soothing

Hans Brough
Hans Brough
~ 4 years ago

imo - by far one of the most useful enhancements to object syntax is the ability to dynamically create an object name (as covered in this vid)

~ 2 years ago

Very cool feature!

Markdown supported.
Become a member to join the discussionEnroll Today