Introduction
ECMAScript 6, also known as ECMAScript 2015 is the next version of Javascript and became a standard in June 2015.
ES6 is a significant update to the language since ES5 back in 2009.
It’s the same old Javascript as we know but with a more beautiful syntax and more features.
It’s goal generally is to be a better language! It lets us code faster, safer and more efficient.
Top Features
- Let + Const.
- Arrow Function
- Rest + Spread Operators
- For-of Loop
- Template Laterals
- Destructing Arrays + Objects
Let + Const:
ES6 provides two new ways to declare variables: let
and const
, which mostly replace the ES5 way of declaring variables, var
. let
works similarly to var
, but it allows block-scoping that is to say that the variables created are only readable within the block in which it’s created. var
is function-scoped.
For instance
if (true) {
var age = 25
};
console.log(age)// returns 25.
//Now replacing the var keyword with the let keyword
if (true) {
let age = 25
};
console.log(age)// This will throw an error because the let keyword is block-scoped which means its only readable within the curly brackets.
const
acts like let
, but the variable you declare must be initialized immediately, with a value that cannot be changed afterwards.
const num = 123;
NOTE: const
means that once the variable is declared, the variable itself can’t be changed. So if the variable is for instance an object, the properties of that object can still be changed.
Arrow Function(=>() ):
The huge arrow function is introduced in ES6 and it simplifies the traditional method of writing Functions.
//Traditional method
function abc () {
return "Hello"
};
abc();// returns "Hello"
//The New Arrow Function
let abc =()=> "Hello"// returns "Hello" also
Passing arguments in the new arrow function can further be simplified but it’s only when passing one argument, the empty brackets can be removed and the function would still run but when passing more than one argument the brackets must be present.
var abc = sum => sum + 2;
console.log(abc(8));// returns 10
Another important thing to know is the behavior of arrow function and the Lexical this
Let’s run some html snippets and create a button called check, using querrySelector to select the button, then try to get the “this” property in both the traditional and the arrow methods of defining functions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button> Check </button>//create a button 'Check'
<script>
var button = document.querrySelector('button');
function abc () {
console.log(this)
};
button.addEventListener('click' abc)
</script>
</body>
</html>
In the above code the lexical this will print the button object because it is the button that called the function abc.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button> Check </button>//create a button 'Check'
<script>
var button = document.querrySelector('button');
var abc2 =()=> console.log(this);
button.addEventListener('click' abc2)
</script>
</body>
</html>
when check button is clicked the lexical this here will print the window object not minding where or what is calling it.
The different properties of the lexical this in the functions above are important notes to take while working or building a project.
Rest and Spread Operators:
Both the rest and the spread operator are written as three consecutive dots (…).
Rest Operator
The rest operator is an amazing addition of the ES6, it kind of converts a list of values or numbers that has been initialized to to an array of values or numbers
You can think of the rest parameter as the opposite of the spread operator. Because just as the spread operator allows you to expand an array into its individual elements, the rest parameter lets you bundle elements back into an array.
Let’s see some examples
const odd = [3,5,7,11,13];
const [a,b,...c] = odd;
console.log(a,b,c);// returns 3 5 [7,11,13]
//another example
const num = [1,2,3,4,5];
function totalSum(sumAll){
var result = 0;
for(i = 0; i < sumAll.length; i++){
result += sumAll [i];
}
return result;
}
console.log(totalSum(num));// returns 15. the summation of number in
array num.
//Consider a situatiion where we are presented with just a list of
//numbers to work with a kind of free arguments.
//the rest parameter will be added to our function argument
function totalSum(...sumAll){
var result = 0;
for(i = 0; i < sumAll.length; i++){
result += sumAll [i];
}
return result;
}
console.log(totalSum(30,40,50,60));// returns 180, which is correct.
Spread Operator
The spread operator was introduced in ES6. It provides you with the ability to expand iterable objects into multiple elements.
One can summarily say that the rest operator collects a list of numbers or values and make an array of numbers while the spread does exactly the opposite it collects an array of numbers or values and form a list of numbers or values.
Let’s see some examples
const num = [1,2,3,4];
const [a,b,c,d] = num;
console.log(c,d);// returns 3 and 4
//let's log the spread operator with the const variable
console.log(...num);// returns 1 2 3 4
// another example
let num = [1,2,3,4,5];//an array of numbers
console.log(Math.max(num));// returns NaN. This is because Math.max is
// a function that uses a list(not array) of numerical values passed as //parameters to return the highest value.
console.log(Math.max(...num);// returns 5, which is what is expected.
//what happened was that from num array list numbers was formed using
// the spread operator(...)
The For-Of Loop.
The for-of
is a new loop in ES6 that replaces both for-in
and forEach()
and supports the new iteration protocol. Used to also loop over iterable objects (Arrays, strings, Maps, Sets).
const iterable = ['a', 'b'];
for (const x of iterable) {
console.log(x);
}
// returns a b
//Another example
//break and continue work inside for-of loops:
for (const x of ['a', '', 'b']) {
if (x.length === 0) break;
console.log(x);
}
// returns a
//Another example
let finalResults = [1.25,2.10,5.2];
for (let myResult of finalResults){
console.log(myResult);
}// return a list of values
// 1.25
//2.10
//5.2
Template literals
Template literals are quite simply the easiest way to improve your JavaScript code readability when working with Strings. They are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
See example
let name = 'Melvin';
let description = `
Hello I'm ${name}`;
console.log(description);// returns Hello I'm Melvin. Awesome
we can accessed our data from inside the string with the ‘$’ sign we can as well add other values inside the curly bracket that holds our name variable.
See example
let name = 'Melvin';
let description = `Hello I'm ${name +' Chidi.'};
console.log(description);// returns Hello I'm Melvin Chidi.
we can even embed calculations in the template provided the calculations are in string form.
Destructuring Array + Object
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.
Array
In destructuring array ES6 made it so easy and simple
let num = [1,2,3.5,4];
[a,b,c,d,e] = num;
console.log(a, b);// return 1 2, just as expected
Now if we try to log [e] to the console it will return undefined because the num array have just four values, so [e] is left out without a value. But we decided to be fair to [e] and added a default value to it.
[a,b,c,d,e = 5] = num;
Now if we log [e] to our console it will return 5, and that’s exactly what we wanted. what if we decide to correct [c] so we get rid of the decimal and have all whole numbers
[a,b,c = 3,d,e] = num;
If we log [c] to our console it will still return 3.5 because it wasn’t undefined, it has been initialized.
That’s to say that we can only edit or add values to undefined variable.
Another important note in destructuring array is how simple we can write our code and still achieve our desired results
let [a,b,c,d,e] = [1,2,3.5,4];
console.log(a+b*e);// returns 12, fewer codes and desired result.
Object
Basically, some of the methods in the array destructuring still holds in the object.
See example
let object = {
name: 'Melvin',
age: 28
welcome: function(){
console.log('Welcome Dear!')
}
let {name, age,welcome} = object;
};
console.log(name,age)//returns "Melvin" 28
//If we call our welcome function
welcome();// it will print "Welcome Dear"
One important thing to note in object destructuring is that we must use the same names in object outside our object block. If at anytime we decide to change any variable inside our object block we would do that thus.
See example
//we are going to change our 'name initial variable to 'myName'
let {name:myName, age,welcome} = object;
// now if we want to access the name value inside our object block we
//will now use myName instead of name
console.log(myName)// returns 'Melvin'
console.log(name)// now throws an error.
Generally, in destructuring array we will be referencing the array position but destructuring object we deconstruct it by name.
What’s next?
This was just a brief introduction to get you familiar with ES6 and its new features. Now you wanna learn more, right? So prepare yourself for lots of awesomeness! Here are some great resources that help you learn more:
- es6features repo explained ES6 features in more details.
Top comments (0)