× {{alert.msg}} Never ask again
Receive New Tutorials
GET IT FREE

Introduction to ES6, Part 2: Template Strings, Destructuring, Function Arguments & Scope

– {{showDate(postTime)}}
This is the second part of Introduction to ES6 series, which is based on the Codementor Office Hours hosted by Jack Franklin. This article will talk about ES6’s template strings, destructuring, function arguments and scope.

Template Strings

Another new feature in ES6 is template strings. Again, this is one of the smaller features that makes things nicer to work with.

We’ve all done that thing where you’ve got a string that you want to output on the screen, and inside it you’ve got to output the value of a variable. It gets dull, it’s difficult to read, and it’s just frustrating to work with. Thankfully now we’re going to get these template strings:

 `In JavaScript ‘ \n’ is a line-feed.`

Instead of starting these strings with double quotes, we start with back ticks instead. It gives us a whole lot of things, so we can output line breaks.

Multi-line strings

var f = `Multiline strings with back ticks in ES6.`
console.log(f);
Multiline strings with back ticks in ES6

This is difficult to show in text, but you can imagine I’ve literally hit Enter and I’m typing back ticks in ES6 on the line below. You can’t do this currently in JavaScript, so this is a way to  structure these big multi-line strings in JavaScript.

String interpolation

String interpolation is more exciting. In the example below, I have a variable name set to jack, and the age to 22.

var name = ‘jack’;
var age = 22;
`${name} is ${age} years old`

I have a template string using back ticks, and then I can use the dollar and the curly braces to insert the variables into the string.  This template will return the string “jack is 22 years old”, and it will have evaluated name and age and kind of put those into the string.

You can have more than just variables in there too. You can do two plus two within those curly braces, you could call a function and whatever that returns will be outputted into the string. Like me, If you come from a language like Ruby, you’ll be familiar with this way of doing things. It’s another really small but really nice improvement that I think makes a big difference.

Destructuring

Destructuring is another small but useful addition to ES6.

Say you have an array of two properties and you want to pull out the first one into a variable called a, and the second one into a variable called b:

var [a, b] = [1, 2];
a == 1
b == 2

Before, you have to do “var = array” and then index zero and “var = array” in index one. Instead we can do this destructuring through the following steps:

  1. Set var and wrap it in square braces “a, b”
  2. Set var [a,b] equal to the array [1, 2]. This destructures the things into the relevant variable.
  3. After running this, A is set to 1 and B is set to 2. This is a really nice way to pull particular bits out of an array that you want to work with.

We can also leave blank spaces out and those will get skipped:

var [a, ,b] = [1, 2, 3];
a == 1
b == 3

So, if you’ve got three items in an array and you only care about the first and last things, you can leave what’s called an array hole in the middle there by putting an empty space between commas. You’ll still get a =1 and b = 3 and the middle value to it will be discarded.

This also extends onto objects too. We use square braces to destructure things out of arrays, and we use curly braces to destructure things out of objects:

var {a, b} = {a: 2, b: 3}
a == 2
b == 3

In the example above, we have an object with properties A and B. If we just want to grab a variable for each of those properties, we can  use curly braces instead.

I’ve used this quite a lot, and the one area I find this really useful is when you’re dealing with responses from APIs.

For example, if you’ve made a query to a particular API, say the Instagram API, to get a bunch of pictures, those pictures have a load of properties on them and you might only care about one or two. Instead of having to pull those off manually, you can just use this destructuring to quickly and easily pull the bits off the objects instead of having to do that by hand. It’s a succinct way of expressing what you want it to.

Notes on Destructuring:

1. Destructuring code fails silently 
var {a, b} = {b: 3}
a == undefined
b == 3

Here I’ve told it to pull the a and b properties off the object, where the object only has b set to 3. It doesn’t error to me, it’s not going to blow up, it’s just going to silently set a to undefined, set b to 3 and move on. This is the good behavior─I think it’s the right way to do it─but it’s kind of worth being aware of. So, if you get a random undefined value it could be because of this.

2. When to Use Object Destructuring

This instance below is an example of when object destructuring becomes really useful:

 function getPerson() {
	return { name: ‘jack’,
		age: 22
		}
};

var {name, age} = getPerson();

If I have a function getPerson which is returning an object, and I want to get either one of those properties (or in this case, both of the properties) off of its variable, I can do it and express it really nicely in that line below.

var {name, age} = getPerson();

I think this really shows the usefulness and power of destructuring, particularly of object. I don’t tend to use the array destructuring as much but there’s some times where that’s been really useful as well.

Function Arguments

Default Function Argument Values

This is a thing that other languages have had for a long time, and it’s nice to see JavaScript catching up to this one.

function getInfo(print=false)
	if(print)  {
		log(this.name, this.age);
	}  else  {
	   return
		`${this.name}  ${this.age}`
	}
}

getInfo();

For example, if I have a getInfo function and it takes a while to print and it prints true, I’m going to log something to the screen. I’m also going to return the string, and it will work as you imagine I’d set print.

In the code, I’d need to set the function equal to false. This means: if print isn’t supplied, just set it to false so you don’t have to worry inside if(print) isn’t defined and set.

Spread Operators

function length(…nums) {
	log(num.length);
};

length(1,2,3); // 3

The dot I’ve got is called the spread operator, and it’s used to take in any number of arguments and convert them into an array.

The function length is going to return whatever length that the thing is given to it. Instead of making the length function take in an array of things, I can just use the spread operator, and this function takes in any number of arguments. By entering …nums, all the arguments passed in the length function are converted into an array for me. In other words, nums is an array in this length function.

When I want to call length with the values 1,2,3, I can just type length(1,2,3).

There’s no more doing array.prototype.slides.callback and its arguments and the arguments object, you get an array of all the arguments. You just use “…” – it’s much easier and much nicer.

The spread operator also serves as a handy shortcut to the case where you’ve got an array of arguments that you need to pass into another function that you want to call:

function total(x, y, z) {
	log(x + y + z);
};
total(1, 2, 3)

In this case above, I have a total function. I had to take the three arguments, X, Y and Z and it just logs out the sum of them. When I call total(1, 2, 3), I’ll get back 6.

However, say I have an array of 1, 2, 3 and I want to call a total function and take each of the items in the array and call it as one of the arguments in the total function.

The current way to do this in JavaScript now is to use apply:

total.apply(null, [1, 2, 3]);

The first item to apply is the scope of the function (in this case, I would just use null.) The second is an array where each one will be mapped onto one of the arguments of the function.

However, now we can use the spread operator to do the exact same thing:

total(…[1, 2, 3]);

This will call total, destructure will rather spread each item in the array to be one argument to the function. It’s a nicer way of expressing what you want to achieve.

Destructuring

We can also use function arguments to do some really cool stuff with destructuring now as well:

function foo( {name, age}) {
	console.log(name, age);
}

foo( { name: ‘jack’, age: 22})

//=> jack, 22

In this case, the function foo expects to be called with an object with two properties: name and age. You see at the top here where I’ve defined it, I’ve given it the curly brackets around the name and age arguments.

So, when I call foo with and object that has name and age properties, it’s going to pull out the name and age properties and make them available to me as variable within the function.

This is useful if you’re looking at function that takes an object and you want to know what properties it particularly cares about. When a function is defined like foo is here, it’s very easy for another developer to look at the source and see what properties you’re expecting to pass through. You can get at just those variables inside the function, which is really useful.

Scope

Although we’ve already mentioned lexical scoping in Part 1, scope is one of the bigger changes to JavaScript coming in ES6 or ES2015.

The Global & Function Scope

Currently in JavaScript, there are two scopes: the global scope, which is the window object in browser world, and the function scope.

In this example above, we have variable foo at the top level, but we miss out the var keyword that goes onto the global scope as  it does for the variable fad because it’s also defined at the global scope.

If I define bar to be 3 and miss out the , the variable also getsout to the global scope. On the other hand, var baz = 4 goes onto the function scope. And traditionally this missing of the var keyword has caused a lot of bugs. So it’s very easy to float up onto the global scope when you didn’t mean it to.

Scope gets confusing, particularly for beginners new to the language, when you define a variable within a block (e.g. an if condition or an allude)

For example, when foo gets defined in the function above, it doesn’t get defined within just the braces of that condition or within the block scope─it gets defined within the function scope. So here, var foo and var baz are both defined on the same level. Once you know the rules around how JavaScript does scoping and it’s just global, it’s easy to see what’s going on here. However, this is kind of unintuitive.

Block Scopes

In ES6, we’ll get a new scope called the block scope.

What we’re going to get in ES6 is a new scope which is called block scope.

Instead of using the var keyword, we can use the let keyword within this if(x) conditional. This means y is only available within the block (anything with curly braces around it). If I used the var keyword, it would be available in the function scope, but the let keyword defines things in the block.

Here is another example:

I think this is really going to solve a lot of bugs, since a lot of times variables end up in a scope you didn’t really imagine them to be in.  Once ES6 is out and they introduce it across most browsers, people should start using let by default. The var keyword shouldn’t really be used. I think it should only be used on the legacy code and over time you can transition to using let instead of var, and replacing your old vars with lets. For new code, when this stuff comes out and is readily available in your browsers, you should be using let from the get-go.


About Jack Franklin

Jack Franklin is the author of the book Beginning jQuery. Jack was also asked by Addy Osmani to contribute to his Backbone Fundamentals book (the chapter on using Backbone and RequireJS specifically.) Jack runs the popular JavaScript Playground blog, on which he writes tutorials about a variety of JavaScript topics including ES6, GoldNote and more. He is currently a developer over at GoCardless and is a regular writer for DotNet, which is the largest web development magazine over in the UK. He wrote the JavaScript Gallery section for a number of months on JavaScript topics, including a recent cover feature on JavaScript libraries.



Author
Jack Franklin
Jack Franklin
Ruby and JavaScript developer from London, UK.
Hire the Author

Questions about this tutorial?  Get Live 1:1 help from JavaScript experts!
Yuriy Linnyk
Yuriy Linnyk
5.0
Webdev Coach • 18yr+ Javascript Developer • 5yr+ CodeMentor.
You can understand it! Whether you're catching up in a coding bootcamp, or nailing a bug — reach me in the chat and we'll figure it out. I know you...
Hire this Expert
Sumit S
Sumit S
5.0
Senior full stack developer
More than 10 years of experience in web/product development(worked at Microsoft for 10 years). Currently working as a Full-stack developer....
Hire this Expert
comments powered by Disqus