top
Lightning Sale

Search

JavaScript Tutorial

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- h2Template 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 BondDefault ParametersDefault 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)); // 2The 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)); // 2Spread Operator and Rest ParametersJust 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.477225575051661We 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 }ES6 Destructuring in JavascriptWith 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.Object DestructuringConsider 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 USADefault ValuesYou 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 USANested Object DestructuringIf there is a nested object as in below-case, we can destructure it by adding it’s value to another object syntaxconst 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.Array DestructuringIt 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
logo

JavaScript Tutorial

Javascript ES6 Features

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- h2

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

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

Spread Operator and Rest Parameters

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 }

ES6 Destructuring in Javascript

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.

Object Destructuring

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

Default Values

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

Nested Object Destructuring

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.

Array Destructuring

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Janani

I have learned many things from this article. It is beneficial for me. Thank you!

Nilesh Chakrabarty

Nice example for beginners.. I m a beginner so this is very helpful for me ... so plz give this type of beginners example..

michael

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.

qtsinfo it

Thanks for sharing the information, it is very helpful, I hope to get more such beautiful blogs from you.

knowledge-wisdom

You have shared great information with me i appreciate your work!

Suggested Tutorials

Node JS Tutorial

Build various types of web applications,command-line application,etc.
Node JS Tutorial

Build various types of web applications,command-line application,etc....

Read More

Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introduced by Google corporation in 2012 and was considered to be one of the most promising among JavaScript frameworks. It was written completely in JavaScript to separate an application’s logic from DOM manipulation, aiming at dynamic page updates. Angular introduced many powerful features enabling the developer to effortlessly create rich and single-page applications.Topics CoveredThis Angular tutorial will span over eight modules, each module covering numerous individual aspects that you need to gain complete information about Angular. This set of modules serves as an Angular tutorial for beginners along with experienced IT professionals.Here are the topics that will be covered in the Angular tutorial:Get started with Angular.Learn the basics of Angular.Know what Angular Directives.Get an idea of Component Inputs and Outputs of Angular.Know about Forms in Angular.About Services in Angular.Pipes in Angular.HTTP, Routing and Building in Angular.Who can benefit from this tutorial?This Angular tutorial will be helpful to IT professionals such as:Software Developers, Web Application Programmers and IT Professionals Software Architects and Testing Professionals Career aspirants in web development
Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introdu...

Read More