Best JavaScript (ES6) Features, that’s can be used in 0b11111100100 (2020).
JavaScript has made significant progress over the past few years. If you are new to JavaScript or have some experience and want to quickly get comfortable with the most commonly used features of modern JavaScript, this post is for you.
In this article I will cover four main features in JS ES6:
1.Arrow Functions
2.Destructuring
3.let
andconst
variables
4.Template literals
All these new/old/renewed features are natively supported in all modern browsers. You can check it on Can I use. For better understanding, I advise you to test the code snippets below and write more code. Only with more code writing experience, you will get the necessary knowledge!
So, let’s move! Fewer words more code…
Arrow Functions
One of the most usable ES6 features. Arrow functions give you a clean and concise syntax for writing function expressions. For Example:
Function expression in ES5:var test = function(a) {
return a * 4;
}Arrow Function in ES6:const test = (a) => {
return a * 4;
}
Arrow functions allow us to write shorter function syntax, we get rid of the function
keyword and put a fat arrow =>
between the parameters and the body of the function.
Next example is the one-liner function that returns the value:
const test = (a) => a * 4;
Here we can drop the return
keyword and curly braces too.
It’s a cleaner code, right?
And what If our arrow function includes only a single parameter? Then we can even drop the parenthesis…
const test = x => x * number;
I love it. We getting really clean code here.
What if our arrow function doesn’t have any parameters? Then we need to use a pair of parenthesis:
const test = () => {console.log('Test Me');};
More arrow function examples:
An empty arrow function returns undefined
let test = () => {};Immediately Invoked Function Expression
(() => 'test')();
// Returns "test"If/Else Statement with arrow function
var simple = a => a > 21? 15 : a;
simple(25); // 15
simple(20); // 20
Browser compatibility
As you can see, arrow functions are very useful and give us an option to write clean and understandable code. The next topic is Template Literals.
Destructuring
What is Destructuring? Destructuring simply implies breaking down a complex structure into simpler parts. In JavaScript, this complex structure is usually an object or an array. With the destructuring syntax, you can extract smaller fragments from arrays and objects. The destructuring syntax can be used for a variable declaration or variable assignment. You can also handle nested structures by using nested destructuring syntax.
Fewer words and more examples. Let’s say we have some object like this:
const cat = {
name: 'Murzik',
age: 3,
address: '111 Find this st'
};
Now, somewhere else we need to access these properties and store their values in a bunch of variables:
const name = cat.name;
const age= cat.age;
const address = cat.address;
We have this repetitive code over and over: “cat” repeated n times. Object destructuring gives us a short and clean syntax to extract the value of multiple properties in an object:
const { name, age, address} = cat;
That’s it! This code is exactly equivalent to the snippet above. We use curly braces on the left to destructure the cat object. Inside the braces, we’re defining 3 variables: name, age, and address. Their values will be extracted from the corresponding properties in the address object.
Note that we don’t have to list all the properties in the address object. Maybe we’re interested only in the age property:
const { age } = cat;
The array destructuring has very much similar functionality with Object destructuring. It’s using square brackets ([]) instead of curly braces ({}).
Let’s see how it works. For example, we have an array and we want to store items from this array in different variables:
// ES5 Old Structure
const colors = ['red', 'green', 'blue'];
const first = colors[0]; (gets 'red')
const second = colors[1]; (gets 'green')
const third = colors[2]; (gets 'blue')With destructuring, we can re-write the above code like this:// ES6 The New One with Array Destructuring
const colors = ['red', 'green', 'blue'];
const [color1, color2, color3] = colors;
console.log(`tone: ${color1}, grass: ${color2}, sky: ${color3}`);
//Result: tone: red, grass: green, sky: blue
Cool, isn’t it.
let and const variables
With JavaScript (ES6), we got 2 new ways to define variables: let
and const
. Prior to ES6, we used the var
keyword. What the difference? var
declarations are globally scoped or function scoped and can be updated and re-declared within its scope. let
and const
are block-scoped. let
variables can be updated but not re-declared. const
variables can neither be updated nor re-declared. Let’s take a closer look at them:
Here are some examples for var
keyword:
function test() {
for (var x = 0; x < 10; x++) {
// Technically, x should only be scoped to this block because this is
// where we have defined x.
} // But it turns out that x is available here as well!
console.log(x); // 10
}
That’s not how most if not all other programming languages behave! Variables defined within a block should be scoped to that block only. In this example, x
should not be accessible outside of the for
block.
Another issue with the var
keyword is that if you use it at the top level outside of a function, it creates a property on the global object:
var test = 10;
console.log(window.test); // 10
Let’s check examples with: let
and const
function test() {
for (let x = 0; x < 10; x++) {
// With the "let" keyword, now x is only accessible in this block.
} // x is out of the scope here
console.log(x); // x is not defined
}
As I said above with const
we can define a constant. So we cannot reassign it later:
const test = 1;
test = 2; // throws "Assignment to constant variable."
One more important thing to know is, unlike the var
keyword, let
and const
don’t create a property on the global object if you use them at the top level:
let test = 10;
console.log(window.test); // undefined
From my experience:
- With ES6 I am trying to use the
var
keyword as less as possible, and to use onlylet
orconst
. - I am using
let
only if I need to re-assign the identifier. Otherwise, I prefer to useconst
to prevent accidentally re-assigning a constant.
Template Literals
Before ES6, we had to deal with these ugly string concatenations:
Old Code version:
var name = 'Codingforweb';
var message = 'Hi ' + name + ',';
Now, with template literals (previously called template strings), we can define a string with placeholders and get rid of all those concatenations:
ES6 code:
var name = 'Codingforweb';
var message = `Hi ${name},`;
Pay attention I’m using the back-tick character here. ES 6 comes up with a new type of string literal, using the back-tick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated. Back-tick character you can find before number 1 on your keyboard.
To add a placeholder in a template literal, we use the ${expression} syntax. You can replace “expression” with any JavaScript expressions. Here, we are adding the name variable there. You can also call a function or pass any JavaScript expressions that result in a value.
Another benefit of using template literals is that they can expand multiple lines. They are particularly useful when composing email messages:
var message = `Hi ${name},Thank you for joining. Happy coding, Codingforweb`;
This is only a small part of the improvements from ES6. Just check them, and if you are still not using them, then start to do it as soon as possible.
That’s all for now. Feel free to join my Telegram channel and Instagram. Thank you for reading and see you later.
Happy Coding