Object Literals and String Interpolation
Last updated
Last updated
After this lesson, you will be able to:
Simplify expressions using object literals
Simplify expressions using template literals
Define imports without global variables
This is the last bit of ES6 we'll check out before doing an exercise!
Object literal shorthand is a simple but useful bit of syntactic sugar. If you want to assign a variable as the value of the key of the same name, you don't have to write it twice. What?
If we declare a variable, price
, and set it equal to 100: const price = 100;
We then have an object called item
. Now, item
also has a variable of how much that item costs, which happens to also be price
. They are different variables (one is global, and the other is specific to the item
object); they just happen to share the same name. So our item
object might be:
Now, let's say that when we initialize item
, instead of hard-coding a number into the initialization, we want to set price
to be whatever the global price is. This global price is also stored in a variable called price
, right?
It looks like this:
It's weird looking, but it works.
Well, it turns out that having two different variables with the same name and setting them equal to each other is a pretty common thing to do. ES6 decided to just simplify this by dropping the duplicate and having it mean the same thing. So now we can do:
Less to write, and less to read when you come back to it. A win-win!
Template literals bring us string interpolation in JavaScript. This means we can create dynamic strings with more readable syntax.
Before ES6, we had:
Now, using template literals, we can make this easier:
Note that now, we can directly refer to the variable using ${} syntax within our string.
In fact, combining an arrow function with a template literal, we can do this:
In ES6, you can import modules directly without declaring them as global variables. This makes namespacing your app a non-issue. Before module imports, namespace was often a primary concern in JavaScript.
So, if you want export my addTwo
function as a module, you can create a file called "addTwo.js":
And in another file, say "app.js", i can import it:
You can also export multiple modules from a file, like so:
And somewhere else: