ES6 Interview Questions: ES6 is also known as ECMAScript 2015.
ES6 Interview Questions
Q:- What is ES6?
  • ES6 is also known as ECMAScript 2015.
  • ES6 or ECMAScript 2015 is a 6th major release of ECMAScript.
  • If your browser doesn't support ES6, then you can write ES6 commpatible code using Babel and Webpack.
  • ES9 (ECMAScript 2018) is the latest verison of ECMAScript.
Q:- What is ECMAScript?

ECMAScript is the specification defined in ECMA-262 standard for creating a general purpose scripting language.

Q:- What is JavaScript?

A general purpose scripting language that conforms to the ECMAScript specification.

You may also like - Node.js Interview Questions Answers
Q:- List some new features in ES6 (ECMAScript 2015)?
New Features in ES6:

Top 10 ES6 Features that every JavaScript Developer must know.

  1. Let and Const Keywords
  2. Arrow functions
  3. Template Literals
  4. Object Literals
  5. Default Parameters
  6. Destructuring Assignment
  7. Rest and Spread Operators
  8. Modules, Classes, Generators in ES6
  9. Promises in ES6
  10. Map and Set Data Structure
1. Let and Const Keywords:
Let Keyword:

ES6 introduces the new let keyword that allows us to declare variables in block scope.

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.

let a = 10; funtion testMe(){ let a = 20; console.log(a); // 20 } console.log(a); // 10

Important Points:-

  • In ECMAScript 2015 (ES6), let and const are hoisted but not initialized.
    Referencing the variable in the block before the variable declaration results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
  • let can not be redclare in same scope.
Const Keyword:
  • const keyword used to define constants in ES6.
  • it is also known as immutable variables.
  • The value of a constant cannot change through reassignment, and it can't be redeclared.
const MY_CONST = "JavaScript"; console.log(MY_CONST); //JavaScript MY_CONST = "ES6"; console.log(MY_CONST); // Uncaught TypeError: Assignment to constant variable, because we cannot re-assign a new value to a constant

In case of Object and Array we can push new items to it

const myObject = { name: "Full Stack Tutorials" }; // If you will attempt to overwrite/reassign/redeclare the object throws an error. myObject = { name: "Full Stack Tutorials" }; //Uncaught TypeError: Assignment to constant variable. myObject = { fullname: "Full Stack Tutorials" }; //Uncaught TypeError: Assignment to constant variable. // Since, object keys are not protected, below code will run successfully. myObject.name = "Anonymous User"; // You can use Object.freeze() to make object immutable const myArray = ["Javascript", "Node.js", "React.js"]; // It's possible to push items into the array myArray.push("jQuery"); // But assigning a new Array to the same variable will throws an error. myArray = ["jQuery"]; //Uncaught TypeError: Assignment to constant variable.
Object.freeze()
Object.freeze works on values and it makes an object immutable.

Object.freeze() takes an object as an argument and returns the same object as an immutable object

Once you have frozen the object you cannot change, add or delete object's properties, but you can assign another instance.

const myObject = {'name': 'Full Stack Tutorials'}; Object.freeze(myObject); myObject.name = 'Anonymous User'; // will throws an error in strict mode console.log(myObject.name); // Output: Full Stack Tutorials
2. Arrow Functions:
  • An arrow function has a shorter syntax than a regular function.
  • In Arrow function there is no existence/binding of this, arguments, super, new.target.
  • An Arrow function takes/inherit this from it's immediate parent scope (lexical scope).
(param1, param2, …, paramN) => { //statements or code }
//in ES5 var sum = function (a, b) { return a + b; }; console.log(sum(10, 40)); // 50 //---------------------------- //in ES6 var total = (x, y) => { return x + y; }; console.log(total(20, 30)); // 50
Important Note:
  • Arrow function are the best choice when working with closures and callbacks.
  • Arrow function is not a good choice when working with class/object methods and constructors.
You may also like - JavaScript Interview Questions
3. Template literals:

ES6 introduce a new and easy to use string templates with placeholders for variables.

  • Template literals are enclosed by the back-tick (` `).
  • You can use multi-line strings.
  • You can use a new syntax ${variable_name} inside of the back-ticked string.
  • Before ES6 it was called Template Strings.
//Example-1 var num1 = 10; var num2 = 20; console.log(`The sum of ${num1} and ${num2} is ${num1 + num2}.`); //Output: The sum of 10 and 20 is 30 //Example-2 var TempBody = `Hello Users! Your are reading about ES6 Features, In ES6, you are implementing Template Literals. Let me show you the sum of ${num1} and ${num2} is ${num1 + num2}. Hope you have understood the concept of Template Literals.`; console.log(TempBody);
4. Object literals:

A JavaScript object literal is a comma-separated list of name-value pairs wrapped in curly braces.

var myObject = { title: 'ES6 Interview Questions and Answers', topic: 'Object Literals', status: true, myFunction: () => { // Block of Code } };
5. Default Parameters:

Default function parameters allow named parameters to be initialized with some default values if no value or undefined is passed.

//parameter c has default value zero. let addNumbers = (a, b, c = 0) => { return a + b + c; } console.log(addNumbers(1, 2, 2)); //5 console.log(addNumbers(5, 20)); //25
6. Destructuring Assignment

Destructuring assignment is a special syntax that allows you to "unpack" arrays or objects into a bunch of variables, as sometimes they are more convenient.

  • Simple Destructuring
  • Assign default value while destructuring
  • Adding an Alias to a Destructured Assignment
  • Adding an Alias to a Destructured Assignment
Simple Destructuring
let arr = ["Full", "Stack", "Tutorials"] // destructuring assignment let [fname, mname, lname] = arr; console.log(fname, mname, lname); //Full Stack Tutorials
Assign default value while destructuring

A variable can be assigned a default, in the case that the value unpacked from the array is undefined

const arr = [, 'two', 'three']; const [a = null, b, c, d] = arr; console.log(a, b, c, d); // null two three undefined
Adding an Alias to a Destructured Assignment

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

let info = {tech: "JavaScript", topic:"ES6"}; let {tech: technology, topic} = info; //we have use technology as alias name for tech. console.log(technology, topic); //JavaScript ES6
Assigning the rest of an array to a variable

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest

const [a, b, ...rest] = [1, 2, 3, 4, 5]; console.log(a); // 1 console.log(rest); //[ 3, 4, 5 ]
You may also like - React.js Interview Questions
7. REST and Spread Operator:
Spread Operator:

It allows the expansion of an iterable (e.g., Array) into its constituent elements.

OR

Spread operator unpacks the collected elements (iterable - Array/Object etc) into single elements.

let a = [1, 2, 3]; let arr = [...a, 4, 5, 6]; //a unpacks into it's constituent elements. console.log(arr); // [ 1, 2, 3, 4, 5, 6 ]

Spread can be used in following CASE.

  1. Array Merge - Adding array elements to an existing array
  2. Copying Arrays
  3. Pass elements of an array to a function arguments
Rest Operator:

It is the collection of all remaining elements into an array.

Rest parameter must be the last parameter in the function. because it collects all remaining arguments into an array.

REST can be used in following CASE.

  1. In Function Parameter
  2. Destructuring the Object/Array
#Example - 1 (Function Parameter) function getInfo(name, ...rest) { console.log(name); // JavaScript console.log(rest); // [ 'Frontend Developer', 'ES6' ] } getInfo("JavaScript", "Frontend Developer", "ES6");
#Example - 2 (Destructuring) let arr = ["JavaScript", "Front-End Developer", "ES6"]; let [name, ...rest] = arr; console.log(name); // JavaScript console.log(rest); // [ 'Front-End Developer', 'ES6' ]

Important Note:-

  • Rest Parameter is collecting all remaining elements into an array .
  • Spread Operator is unpacking collected elements such as arrays into single elements .
Example:- Remove duplicates items from an array using ES6 Set?
The Set object lets you store unique values of any type, whether primitive values or object

Here’s a one-liner to remove duplicates from an array. (ES6, of course!)

const numbers = [1, 2, 3, 4, 5, 5, 5, 5, 5, 5]; function removeDuplicates(array) { return [...new Set(array)]; } console.log(removeDuplicates(numbers)); // [1, 2, 3, 4, 5]

Set was introduced in ES6 and is similar to the Sets we encounter in Mathematics: They can’t have duplicates. After we have done that, we simply convert the Set back to an array by using the spread operator.

8. Class In ES6:

In ES6, JavaScript classes provide the following advantage over prototype based.

  • Syntactic sugar - follow OOP Approach (extends etc).
  • Inheritance - JS class inheritance is still prototype-based under the hood.
  • It has Static methods - which are called on the class itself only.
class User{ constructor(name, age) { this.name = name; this. age = age; } getUserDetails() { console.log(this.name + " is " + this. age + " years old!"); } } var userObj = new User("Full Stack Tutorials", 5); console.log(userObj.getUserDetails()); //Output: Full Stack Tutorials is 5 years old!
Generators

A generator is a function that can stop midway and then continue from where it stopped.

In short, a generator appears to be a function but it behaves like an iterator.

function* process() { console.log('Start process 1'); console.log('Pause process2 until call next()'); yield; console.log('Start process 2'); console.log('Pause process3 until call next()'); yield; console.log('Start process 3'); console.log('End of the process function'); } let _process = process(); let _process = process(); _process.next(); _process.next(); _process.next();
yield:
  • yield keyword simply helps to pause and resume a function in any time asynchronously.
  • Additionally it helps to return value from a generator function.
Usages:
  • Lazy evaluation
  • Infinite sequences
  • Asynchronous control flows
9. Promise:
Promises are used to handle asynchronous operations in JavaScript.

A promise is an object which can be returned synchronously from an asynchronous function.

Promise overcome the problem of callback hell.

Promise States:
  • Fulfilled: onFulfilled() will be called (e.g. resolve() was called).
  • Rejected: onRejected() will be called (e.g. reject() was called).
  • Pending: initial state, neither fulfilled nor rejected.
Promise Consumers: then, catch, finally
let promise = new Promise(function (resolve, reject) { let A = true; let B = true; if (A === B) { resolve(); } else { reject(); } }); promise .then(() => { console.log("Success, promise resolved"); }) .catch(() => { console.log("Error!, promise rejected."); });
10. Map & Set:
Map:

Map is a collection of keyed data items, just like an Object.

Note - Map allows keys of any type.

  • new Map() – creates the map.
  • map.set(key, value) – stores the value by the key.
  • map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
  • map.has(key) – returns true if the key exists, false otherwise.
  • map.delete(key) – removes the value by the key.
  • map.clear() – removes everything from the map.
  • map.size – returns the current element count.
map = new Map() map.set("website", "Full Stack Tutorials") map.set("topic", "JavaScript ES6"); console.log(map); //Output /* Map { 'website' => 'Full Stack Tutorials', 'topic' => 'JavaScript ES6' } */
Set:

Set is a collection of unique data items, without keys.

  • new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
  • set.add(value) – adds a value, returns the set itself.
  • set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
  • set.has(value) – returns true if the value exists in the set, otherwise false.
  • set.clear() – removes everything from the set.
  • set.size – is the elements count.
Q:- Difference between Arrow Function and Normal Function in JavaScript?

There are following differences between Arrow Function and Normal (Regular) Function:

1. Syntax:

Both Arrow Function and Normal (Regular) Function has different syntax.

//Normal Function: let func = function myFunc(params){ // body of the function }; OR function myFunc(params){ // body of the function };
//Arrow Function: let func = (params) => { // body of the function };
2. Use of this keyword:
In Arrow functions there are no binding of this

Unlike regular functions, arrow functions do not have their own this.

let myFunc = { name: "Full Stack Tutorials", regFunc() { console.log(`Welcome to, ${this.name}`); // 'this' binding works }, arrowFunc: () => { console.log(`Welcome to, ${this.name}`); // no 'this' binding } }; myFunc.regFunc(); myFunc.arrowFunc();
3. Using new keyword:

Arrow functions cannot be used as constructor with new, it will throw error.

let myFunc = () => {}; let func = new myFunc(); // Uncaught TypeError: myFunc is not a constructor
4. Availability of arguments objects:

Arrow functions don't have their own arguments object. Therefore, arguments is simply a reference to the arguments of the enclosing scope.

5. Use of prototype property:

Arrow functions do not have a prototype property.

let myFunc = () => {}; console.log(myFunc.prototype); // undefined
Q:- List some new features in ES7 (ECMAScript 2016)?
New Features in ES7:
  1. Array.prototype.includes()
  2. Exponentiation operator
Array.prototype.includes():
let arr = [1,2,3,4,5]; console.log(arr.includes(5)); // true console.log(arr.includes(15)); // false let arrOfStr = ["Apple", "Banana", "Grapes"]; console.log(arrOfStr.includes("Apple")); // true console.log(arrOfStr.includes("apple")); // false
Exponentiation operator:
let a = 10; console.log(a ** 2); // 100
Q:- List some new features in ES8 (ECMAScript 2017)?
New Features in ES8:
  1. Async/Await
  2. Padstart and Padend functions
Async/Await:
async function getData(url) { try { let result = await apiCall(url); console.log(result); } catch (error) { console.log("ERROR!,", error); } } getData(url);
PadStart and PadEnd functions:
let str = "JavaScript"; console.log(str.padStart(11, "#")) // #JavaScript console.log(str.padStart(10, "#")) // JavaScript console.log(str.padStart(12, "#")) // ##JavaScript console.log(str.padEnd(11, "#")) // JavaScript#