While going through some of the
java script ES6 standards, I came across below 4 very useful
features which can be very handy in daily use. I am keeping it as a note from a learning site.
·
Template
literals –
Before ES6, we had to deal with these ugly string
concatenations:
var name = Krishna';
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:
var name = ‘Krishna';
var message = `Hi ${name},`;
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 my mailing list.
Happy coding,
Krishna
`;
·
Let and Const
–
we used the var keyword to define variables. The scope of
a variable defined using the var keyword is the entire enclosing function.
Here’s an example:
const x = 1;
x = 2; // throws "Assignment to constant variable."
let x = 1;
console.log(window.x); // undefined
So, here is
what you should take away:
·
Ditch the var keyword.
Use only let and const.
·
Prefer const to let.
Use let only if you need to re-assign the identifier; otherwise,
use const to prevent accidentally re-assigning a constant.
·
Arrow
Functions –
Inspired by lambda expressions in C#, arrow functions
give you a clean and concise syntax for writing function expressions. Here’s a
function expression in ES5:
const square = function(number) {
return number * number;
}
With arrow function:
const square = (number) => number * number;
·
Destructuring –
Destructuring is an expression that allows us to extract
properties from an object, or items from an array. Let’s say we have an address
object like this:
const address = {
street: '123 Flinders st',
city: 'Melbourne',
state: 'Victoria'
};
Now, somewhere else we need to access these properties
and store their values in a bunch of variables:
const street = address.street;
const city = address.city;
const state = address.state;
If we are using ES6:
const { street, city, state } = address;
Object
destructuring is particularly useful when you’re dealing with nested objects:
const
person = {
name:
'Mosh',
address:
{
billing: {
street:
'123 Flinders st',
city: 'Melbourne',
state: 'Victoria'
}
}
};
Without destructuring, we would have to write this ugly
and repetitive code:
const
street = person.address.billing.street;
const
city = person.address.billing.city;
const
state = person.address.billing.state;
// So
annoying!
Now, we can achieve the same result using a single line
of code:
const
{ street, city, state } = person.address.billing;
We can try all these into
our browser console.