JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6) provides syntactic sugar that makes it easier and more concise to write code. In this series, we will discuss some of the interesting features of JavaScript ES6.
Let’s get started…
Let and Const
JavaScript let and const are two new types of variable declarations introduced in ES6 (ECMAScript 2015). These declarations are similar to the var keyword but offer additional features that make them more powerful and easier to use.
Variables were formerly always declared with the var
keyword. This was easier to make mistakes re-declaring variables without realizing it or create shared globally in event handlers where you intended to provide unique values. One of the key differences between let and const is that variables defined with let can be changed with new values, but variables declared with const cannot. This implies that you cannot modify the value of a variable once you have declared it with the const keyword. We will use var
, let
and const
in this example:
var name = "John Doe";
var country = "USA";
var age = 18;
let country = "USA";
country = "Canada"; // This is allowed
On the other hand, you cannot reassign a variable declared with const:
const name = "John Doe";
name = "John Smith"; // This will throw an error
Variables defined with const must be initialized at the moment of declaration, which is another difference between let and const. This implies that when you declare a variable, you must provide it with a value. For example:
const houseNumber; // This will throw an error
Contrarily, initialization is not required when a variable is declared with the let syntax. You can initialize them at a later time as follows:
let age;
age = 22; // This is allowed
Overall, the ways to declare variables in JavaScript are more powerful and versatile thanks to let and const. They provide you more control over your variables' scope and mutability, which can result in code that is clearer and easier to maintain.
Arrow Functions
The arrow function
is one of the newest and most popular syntax that was introduced in JavaScript ES6. The major key difference between the tractional function syntax and the arrow function is the use of fat arrow
=>
.
Let’s declare a multiplication function using both functions:
const multiply = function(x,y) {
return x * y;
}
multiply(5,6);
function multiply(x, y {
return x + y;
}
multiply(5,6);
Arrow function
const multiply = (x,y) => {
return x * y;
}
multiply(5,6);
We can implicitly return it when we have a single JavaScript expression.
const multiply = (x,y) => x * y;
multiply(5,6);
The function
keyword has been replaced with the fat arrow =>
, and the function body is now wrapped in curly braces {}
. This syntax can make your code more concise and easier to read, especially when defining short functions or functions that are used as callback functions.
The fact that arrow functions instantly associate the term "this" with the current context is another benefit of using them. The "this" keyword in traditional function syntax can be challenging to manage, especially when working with nested functions or callback functions. You don't have to worry about binding "this" with arrow functions since it will always be set to the right value.
Let’s look at more advanced arrow function examples:
const numbers = [1, 2, 3, 4, 5];
// traditional function syntax
numbers.map(function(number){
return 2 * number;
)};
// arrow function syntax
numbers.map(number => {
return 2 * number;
});
// refactored arrow function syntax
numbers.map(number => 2 * number);
The arrow function syntax is shorter and simpler to understand than the traditional function syntax. This can improve the readability and maintainability of your code, especially when dealing with big codebases.
Template Literals
Template literals which is also known as template strings are defined using backtick (`)
characters instead of single or double quotes. The template string is just a way of joining JavaScript variables with a string. This allows you to define strings that span multiple lines and that contain expressions that are evaluated and inserted into the string. Here is an example of a template string:
const getFullYearMessage = () => {
const year = new Date().getFullYear();
return "The year is " + year;
}
getFullYearMessage()
We can now refactor to make it more concise using a template string using (`)
and the $
sign.
const getFullYearMessage = () => {
const year = new Date().getFullYear();
return `The year is ${year}`;
}
getFullYearMessage()
//more concise template string
const getFullYearMessage = () => {
return `The year is ${new Date().getFullYear()}`;
}
getFullYearMessage()
Template literals are defined using backtick characters and can be used to create multi-line strings.
Map Helper
The more function is one of the most widely used JavaScript ES6 functions.
The map
method takes a callback function as an argument, executed for each array element. The callback function takes three arguments: the current element, the current index, and the array itself. The callback function should return the transformed element, which will be added to the new array and this helps us to avoid mutation. Here is an example of how the map
method can be used:
let numbers = [1, 2, 3, 4, 5];
let multipliedNumbers = [];
for (let i = 0; i < numbers.length; i++) {
multipliedNumbers.push(numbers[i] * 2 );
}
multipliedNumbers
now let’s map this example using map and arrow function
let numbers = [1, 2, 3, 4, 5]; let multipliedNumbers = [];
let multipliedNumbers = number.map((number) => number * 2);
Using the map method is that it allows you to transform the elements of an array without mutating the original array.
Reduce Helper
The reduce
is so flexing that we can probably re-implement most of the JavaScript helper functions.
The reduce
method takes a callback function as an argument, executed for each array element. The callback function takes four arguments: the accumulated value, the current element, the current index, and the array itself.
Here is an example using the for
loop:
let numbers = [10, 20, 30, 40, 50];
let sum = 0;
for (let i = 0; i < numbers. length; i++) {
sum += numbers[i];
}
Another concise example using reduce :
let numbers = [10, 20, 30, 40, 50]; let sum = 0;
sum = numbers.reduce((sum, number) => { return sum + number; }, 0);
The callback function is executed for each element of the numbers
array and updates the accumulated value by adding the current element. The updated value is then returned, and it is used as the accumulated value for the next iteration.
The reduce
method is that it allows you to perform operations on the elements of an array without mutating the original array.
Rest Operator
The rest operator is used in function arguments when you want to capture a list of variables or a list of arguments. The rest operator is used to gather variables.
This can be very helpful when using indefinite arity(variadic) functions, which are functions that accept a variable number of parameters.
The rest operator is a powerful tool for working with arrays in JavaScript, and can make it much easier to write functions that can handle a variable number of arguments. For example:
const multiplyNumbers = (...numbers) => {
return numbers.reduce((multiply, number) => {
return multiply * number
}, 1);
}
multiplyNumbers(5,10,15,20,25,30,35,40,45,50);
Spread Operator
The spread operator is used to flatten or spread out a list of variables or arguments. The spread operator is represented by three dots (...) and can be used to expand an array into individual elements. For example:
const oddNumber = [1, 3, 5, 7, 9, 11, 13, 15];
const evenNumber = [2, 4, 6, 8, 10, 12, 14, 16];
mergedNumber = [...oddNumber, ...evenNumber];
Destructuring
Destructuring is another ES feature that is frequently utilized. Destructuring provides us with flexibility while writing code.
Destructuring allows you to extract values from objects and arrays and assign them to individual variables. Destructuring can be a very convenient way to extract values from complex data structures in JavaScript.
// Array destructuring
const numbers = [30, 60, 90, 120, 150];
const [first, second, third, ...rest] = numbers;
console.log(numbers);
Let’s look at object
destructuring:
// Object destructuring
const userProfile = {
name: "John Doe",
age: 18,
email: "johndoe@example.com",
country: "USA"
}
let {name, age, email, country} = userProfile;
console.log(userProfile)