New Operators introduced in ES6
Hey readers, welcome to my first blog, in this blog you will learn about new operators those were introduced in ES6.
Javascript offers many operators nowadays out of which below are some special ones.
- Spread & Rest operator (…)
- Arrow operator ( =>)
Spread (…) operator
It allows us to expand the collected elements of an iterable data type like strings, arrays, or objects into individual elements in places.
Usage of the spread operator
To copy an array
let arr1 = [10, 20, 30];
let arr2 = [...arr1];
console.log(arr2); // will return [10, 20, 30]
To concat (Merge) an array
let arr1 = [10, 20, 30];
let arr2 = [1, 2, 3];let arr3 = [...arr1, ...arr2]; // merging two arrays
console.log(arr3); // will return [10, 20, 30, 1, 2, 3]
To destructure an object
let obj1 = {
name: "John",
age: 35,
country: "India"
};
let {name, age, ...rest } = obj1;
console.log(name + " " + age); // will return John 35
To create an array of characters from a string
let text = "string";
let arr1 = [...text];
console.log(arr1); // will return ["s", "t", "r", "i", "n", "g"]
Rest (…) Operator
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
function sum(...rest) {
return [...rest].reduce((total, el) => total + el);
};
sum(1, 2, 3); // will return 6
sum(1, 2, 3, 4, 5); // will return 15
In the above code, we can call the sum() function with the ‘n’ number of arguments. Rest operator will take all the arguments as an array in function.
Here, I used the reduce() function to calculate sum of an array element.
Arrow (=>) Operator/Function
It provide us with a new and shorter syntax for declaring functions.
Let’s compare the normal function declaration and the arrow function declaration in detail:
// Traditional Function Expression
var add = function(a, b) {
return a + b;
};// Arrow Function Expression
var arrowAdd = (a, b) => a + b;
Difference between the traditional function expression and the arrow function
- The biggest difference between the traditional function expression and the arrow function is the handling of this keyword.
- In the arrow functions, there is no binding of this keyword.
var obj1 = {
valueOfThis: function(){
return this;
}
}
var obj2 = {
valueOfThis: ()=>{
return this;
}
}
obj1.valueOfThis(); // Will return the object obj1
obj2.valueOfThis(); // Will return window/global object
- As you can see in the code above, obj1.valueOfThis() returns obj1, since this keyword refers to the object calling the function.
- The this keyword inside an arrow function does not refer to the object calling it. It rather inherits its value from the parent scope which is the window object in this case.
- Therefore, in the code above, obj2.valueOfThis() returns the window object.
Thank you 😊