ES6 or ES2015 was a major update to JavaScript nearly after 20 years of its release. With JavaScript reaching a new high with the popularity of NodeJS, Angular and ReactJS these new features were added to the language. Some of them were syntactic sugar to the language, others were much-needed changes.
We have looked into some of them throughout the series but will look into most of them here.
Template strings are the new way to write Strings in JavaScript and been introduced in ES6. We can now write Strings using back-ticks(``), which have a special way to interpolate variables.
Consider we want to show the famous Bond Line in our console. We declare a variable name and want to display it inside it.
The old JavaScript way is quite cumbersome and we have to use many + operators to concatenate Strings, whereas with back-ticks we interpolate variable name using ${}.
let name = "Bond"; let bondLine = "My name is " + name + ", James " + name; console.log(bondLine); // My name is Bond, James Bond let bondLineES6 = `My name is ${name}, James ${name}`; console.log(bondLineES6); // My name is Bond, James Bond
Default parameters are the parameters, which are used if we don’t pass any value to an argument in a function.
We will see how we use to handle this situation before ES6 if the user didn’t supply a value to the argument. So, we check inside the function “add” if “a” has a value or assign 0 to it. Same is done for “b”.
var add = function(a, b){ a = a || 0; b = b || 0; return a + b; } //Passing no argument console.log(add()); // 0 //Passing argument 'a' console.log(add(1)); // 1 //Passing argument 'b' console.log(add(undefined, 2)); // 2
The same can be done in ES6 by changing the parameter to contain the default value. Re-writing the above with ES6 default parameters.
let add = (a=0, b=0) => { return a + b; } //Passing no argument console.log(add()); // 0 //Passing argument 'a' console.log(add(1)); // 1 //Passing argument 'b' console.log(add(undefined, 2)); // 2
Just like plus(+) and minus(-) are operators, spread(…) is also an operator in JavaScript. Basically Spread operator spreads on demand.
When you pass arguments using Spread operators they are called Rest parameters.
Consider the below example for arrFunc. We can pass any number of arguments to a function and use the …arr to get it. Now inside the function, the arr gets converted into an array. This functionality is quite similar to the arguments object.
Now see the restFunc, here we are using the rest parameter to get the remaining of the arguments. We can get argument a, b, c and then the rest is converted into an array.
let arrFunc = (...arr) => { console.log(arr); } arrFunc(1, 2, 3, 4, 5); //Output - [ 1, 2, 3, 4, 5 ] let restFunc = (a, b, c, ...n) => { console.log(`a, b, c are- ${a} ${b} ${c}`); console.log(n); } restFunc(1, 2, 3, 4, 5, 9 , 8, 7); //Output - a, b, c are- 1 2 3 //[ 4, 5, 9, 8, 7 ]
The Spread operator can be use separately from function parameter and have some very useful use in array manipulation. They can now also be used with Objects.
Consider that we want to copy an array to another array. Now as you can see in the problem that when we assign variable y to x, we are referencing it and any changes to y will reflect in x.
In the first solution, we use the new Javascript method Object.assign() to copy all contents of “a” to an empty array and then assigning it to “b”.
But the better and simple solution is with Spread operator where we spread the array “c”, and take its content in an array.
//Problem let x = [1, 2, 3, 4]; let y = x; y.push(5); console.log(y); // [ 1, 2, 3, 4, 5 ] console.log(x); // [ 1, 2, 3, 4, 5 ] //Solution let a = [1, 2, 3, 4]; let b = Object.assign([], a); b.push(9); console.log(a); // [ 1, 2, 3, 4 ] console.log(b); // [ 1, 2, 3, 4, 9 ] //Solution with Spread let c = [1, 2, 3, 4, 10]; let d = [...c]; d.push(13); console.log(c); // [ 1, 2, 3, 4, 10 ] console.log(d); // [ 1, 2, 3, 4, 10, 13 ]
One other use of Spread operator is to merge two or more arrays like below.
let x = [1, 2]; let a = [3, 4]; let c = [9, 10]; let d = [...x, ...a, ...c]; console.log(d); // [ 1, 2, 3, 4, 9, 10 ]
Another use it that if we pass an array to argument of function or build in functions, which expects arguments. Consider the below examples.
let a = [1, 2, 3, 4]; //Passing array as arguments let arrFunc = (...arr) => { console.log(arr); } arrFunc(a); //[1, 2, 3, 4] //Using inbuilt functions console.log(Math.min(...a)); // 1 console.log(Math.max(...a)); // 4 console.log(Math.hypot(...a)); // 5.477225575051661
We can also use Spread operator in Objects. This is practically used in reducer in React. So, by it we can do both clone and merge as shown in below example. Notice, that in mergedObj foo is “baz” as Object cannot have duplicate keys.
var obj1 = { foo: 'bar', x: 42 }; var obj2 = { foo: 'baz', y: 13 }; var clonedObj = { ...obj1 }; console.log(clonedObj); // Object { foo: "bar", x: 42 } var mergedObj = { ...obj1, ...obj2 }; console.log(mergedObj); // Object { foo: "baz", x: 42, y: 13 }
With the destructuring syntax, you can extract small fragments from arrays and objects. Destructuring syntax can be used in variable declaration or variable assignment. You can also handle nested structure by using nested destructuring syntax.
Consider the below example. Basically, you use an object literal on the left-hand-side of an assignment expression for object destructuring.
const developer = { firstname: 'Tom', lastname: 'Alter', country: 'USA' }; // Object Destructuring const { firstname, lastname, country } = developer; console.log(firstname, lastname, country); // Tom Alter USA
You can pass default values to be assigned to variables in which no values are passed.
const developer = { firstname: 'Tom', lastname: 'Alter', country: 'USA' }; // Object Destructuring const { firstname, lastname, country } = developer; console.log(firstname, lastname, country); // Tom Alter USA
If there is a nested object as in below-case, we can destructure it by adding it’s value to another object syntax
const student = { name: 'Sam Parker', age: 5, scores: { maths: 74, english: 63 } }; const { name, age, scores: {maths, english} } = student; console.log(`${name} who is ${age} years old, scored ${maths} in Maths and ${english} in English.`); // Sam Parker who is 5 years old, scored 74 in Maths and 63 in English.
It is similar to object destructuring, but here instead of keys, you assign any variable.
const rgb = [255, 200, 0]; // Array Destructuring const [red, green, blue] = rgb; console.log(`R: ${red}, G: ${green}, B: ${blue}`); // R: 255, G: 200, B: 0
I have learned many things from this article. It is beneficial for me. Thank you!
Nice example for beginners.. I m a beginner so this is very helpful for me ... so plz give this type of beginners example..
This is a great introduction to variables in JavaScript! As a beginner to JavaScript, I found this guide very helpful in understanding the basics of variables and how they are used in JavaScript.
Thanks for sharing the information, it is very helpful, I hope to get more such beautiful blogs from you.
You have shared great information with me i appreciate your work!
Build various types of web applications,command-line application,etc....
Introduction: Angular (What is Angular?)Angular was formerly introdu...
Leave a Reply
Your email address will not be published. Required fields are marked *