Hello folks,
ES6
, pretty much hyped topic these days in front-end world.
So, how about learning some cool features of ES6 and Beyond (like, ES7, ES8).
First thing first.
What
ES
means?
ES
stands for ECMAScript
.
What is the different between
ECMAScript
andJavaScript
then?
-
ECMAScript
is the standard whereasJavaScript
is also the standard. But, -
ECMAScript
is specification whereasJavaScript
is the implementation ofECMAScript
specifications.
So, let's get started.
What we are going to learn?
let
const
- Object Rest/Spread properties
- Arrow Function
- String interpolation
- Exponential
**
Array.prototype.includes
String.prototype.padStart
String.prototype.padEnd
Object.values
Object.entries
Let
let
is the new var
but the advantage is that it is accessible & available within the scope only.
Let's see an example.
function let_n_var() {
console.log(foo);
if(true) {
let foo = 'foo';
}
}
let_n_var();
// Output: Uncaught ReferenceError: foo is not defined
In the above example, if you replace let
with var
, the output would be undefined
and there will be no error. So, as you can see, let
helps us to catch early errors and no scope mess.
Const
This is again a new way to declare var
but the difference is that once a const
is defined, we can not re-assign a value to it.
const baz = 'baz';
console.log('baz: ', baz);
// Output: baz
baz = 'baaz'
// Output: Uncaught TypeError: Assignment to constant variable.
As we know that JavaScript is dynamic language and we tend to do mistakes while updating the variables with different data type or data, const
helps us to not override the values once set.
Object Rest/Spread properties
Let's look at it by example.
// Rest
const vowels = ['A', 'E', 'I', 'O', 'U'];
const [firstVowel, secondVowel, ...restVowels] = vowels;
console.log(firstVowel); // Output: 'A'
console.log(secondVowel);// Output: 'E'
console.log(restVowels); // Output: ['I', 'O', 'U']
In the above code snippet, I am trying to get the values from variable vowels
into separate variables for first two vowel and remaining as restVowels variable.
Here are the steps to achieve the same.
- Create a variable with array notation:
[firstVowel, secondVowel]
. Assign it thevowels
variable. This will give us first two vowels in respective variables (based on index) - Now, part of third value in array notation, use
...
with a variable name. eg.restVowels
. So, the variable will look likeconst [firstVowel, secondVowel, ...restVowels] = vowels;
- When code executes, it will create variables with values shown above. The alternate way of achieving the same result could be:
const firstVowel = vowels[0];
const secondVowel = vowels[1];
const restVowels = vowels.slice(2); // all remaining values
But, rest approach makes code more readable and manageable.
Here is the code sample for spread considering the above code block (used for rest)
// Rest
const vowels = ['A', 'E', 'I', 'O', 'U'];
const [firstVowel, secondVowel, ...restVowels] = vowels;
// Spread
const vowelsWithOneConsonant = ['B', ...vowels];
console.log(vowelsWithOneConsonant); // Output: ['B', 'A', 'E', 'I', 'O', 'U']
As you can see above, it is very easy to spread the variable vowels to create a new variable with same and one added value too.
These same concepts can be applied on objects too. Go ahead and do some practice. It is fun to use once you learn get used to it.
Arrow Function
This is short hand notation of function
but the binding of this
works differently.
Let's understand the syntax first.
// standard way of defining function
function getName() {
console.log('getName function');
}
// converted to arrow function
const getName = () => {
console.log('getName function');
}
This becomes more interesting and simple when returning values from function.
const getName = (name) => 'Hello' + name;
console.log(getName('Anand')); // Output: Hello Anand
At first glance, it may look confusing but lets break down the code little bit.
- We have created a
const
variable namedgetName
- Assigned a function shorthand used for arrow function
() => {//function body}
- By default, arrow function do not need any
{}
brackets if our code do not expect more than one line. Use curly brackets if we need to. Without curly bracket, arrow function returns the executed code line. In the above example, it returnsHello Anand
So, the above code can also be written as shown below and the output will be same.
const getName = (name) => {
return 'Hello' + name;
}
console.log(getName('Anand')); // Output: Hello Anand
After some practice, you will get it. Go ahead, fire up the browser console and do some practice. An exercise for you is to check how this
behaves with arrow function in comparison to the normal function.
String interpolation
Early days in javascript, if we need to create string with some dynamic values, we used to use +
. Sooner or later, it gets more confusing if it gets really bigger.
So, the string interpolation came to rescue. The syntax is to use back-tick instead of single/double quotes. And, ${}
helps us to put dynamic data without worrying about opening/closing of the sentance or going wrong about missing +
or single/double quotes.
Lets look at the example below:
// Old approach
var guest = 'all';
var name = 'Anand';
var age = 32;
var hobby1= "listening to music";
var hobby2 = "mobiles games";
const sayHello = "Hello " + guest + "! My name is " + name + ". My age is " + age + " years. My hobbies are " + hobby1 + ", "+ hobby2 + '.';
console.log(sayHello); // Output: Hello all! My name is Anand. My age is 32 years. My hobbies are listening to music, mobiles games.
I am sure, it is already looking confusing to you guys. Now look at the below example.
// New approach
const guest = 'all';
const name = 'Anand';
const age = 32;
const hobby1= "listening to music";
const hobby2 = "mobiles games";
const sayHello = `Hello ${guest}! My name is ${name}. My age is ${age} years. My hobbies are ${hobby1}, ${hobby2}.`;
console.log(sayHello); // Output: Hello all! My name is Anand. My age is 32 years. My hobbies are listening to music, mobiles games.
Isn't that cool. 😎
Exponential
I am sure you all know Exponent in mathematics. In Javascript, we used to use Math.pow(5, 6); // Output: 15625
to get the exponent.
Now, we have a short hand to get the same result by doing 3 ** 4; // Output: 15625
.
So, we can say following:
Math.pow(5, 6) == 5 ** 6;
Array.prototype.includes
As it's name suggests, we can use includes
to get true
or false
result value by checking if the value is included or not.
Example:
[1, 2].includes(1); // true
[1, 3].includes(2); // false
var foo = 'foo';
foo.includes('f'); // true
foo.includes('F'); // false
// So, it is case sensitive too. Please take care.
String.prototype.padStart/String.prototype.padEnd
This one is quite interesting. Lets define it first.
padStart
and padEnd
is used to pad the current string with another string until the given string length reaches.
padStart
applies padding from start (left) of the string. On the other hand padEnd
applies padding from end (right) of the string.
These functions can apply padding to the current string with another string multiple times as well, if needed.
Let's have a look to an example
// padStart
const cardNumber = '1234567812345678';
const last3Digit = cardNumber.slice(-3);
const maskedCardNumber = last3Digit.padStart(16, 'X');
console.log(maskedCardNumber); // Output: "XXXXXXXXXXXXX678"
// padEnd
const loremIpsum = "Lorem Ipsum is simply dummy text of the printing and";
const loremIpsumWithDots = loremIpsum.padEnd(loremIpsum.length+3, '.');
console.log(loremIpsumWithDots);
// Output: Lorem Ipsum is simply dummy text of the printing and...
How cool is that? It is pretty interesting and useful. Do practice though.
Object.values
Earlier, we used to use Object.keys
if we need to iterate over an object. But now, we can use values or entries instead keys as per our need.
So, with Object.values
, it returns all the enumerable properties values as an array. Then, it is easy to consume these values directly.
Example:
const objectFoo = {
name: 'foo',
isAvailable: false
};
Object.values(objectFoo);
// Output: ['foo', false]
Object.entries
On the other hand, Object.entries
also gives an array but it contains object's own enumerable string key property [key, value]
pairs. The order remains same as in provided by for...in
.
Example:
const objectFoo = {
name: 'foo',
isAvailable: false
};
Object.entries(objectFoo);
// Output: [['name', 'foo'], ['isAvailable', false]]
Summary
That's it for this post.
We learnt some of the key and useful features of ES6+
. Do practice at your own. Put down comments as a feedback. Do show some love 💗 too and do not forget to share it.
Update[May 5, 2019], part 2 is out. Here is the link. https://dev.to/elanandkumar/es6-and-beyond-part-2-p9m
Top comments (6)
Good article and good uses cases for pad.
May I suggest a clearer example for
let
. While your example is correct, I think this really drives block scope context home:Also, regarding
const
(which is also blocked scoped),It should be noted that this only applies to the value assignment. Nested values are still mutable:
however, the value of a
const
cannot be changed:Thank you.
I do agree with your examples above. Thanks for providing the same.
I did want to cover mutation and more in depth but on the other hand, I just wanted to keep things simple.
Fair enough. It can be hard to keep things simple yet cover all the foundations :)
Thank you.
String interpolation also called template literals right?
And you can use expressions in the literals like:
${ var_1 + var_2 }
Yes, and the example given by you works well. Just make sure to use backtick :)