Posted on: March 14, 2022 Posted by: India Hires Comments: 0
ES6 interview questions

ES6 interview questions, Top Es6 Interview Questions

Are you a qualified ECMAScript programmer who works on client-side scripting on the internet? If yes, then more training in ECMAScript 6 will certainly help you to crack ES6 interview questions and open the door to more opportunities for you. As an ECMAScript 6 developer, you will be able to use a new syntax to write more complex applications that involve various classes and modules.

With features such as arrow functions, typed arrays, and math improvements, you can train yourself to build larger applications as well as libraries. IndiaHires will provide you all the information as to how you can crack ES6 interview questions and answers 2022

es6 Interview Questions   Answers

ES6 interview questions list

  1. What is ES6?Define ES6 and mention the new features of ES6?
  2. Could you explain the difference between ES5 and ES6?
  3. Explain about Internationalization and localization?
  4. What is IIFEs (Immediately Invoked Function Expressions)?
  5. When should I use Arrow functions in ES6?
  6. What are the differences between ES6 class and ES5 function constructors?
  7. Why do we need to use ES6 classes?
  8. What is Hoisting in JavaScript?
  9. What is the motivation for bringing Symbols to ES6?
  10. What are the advantages of using spread syntax in ES6, and how is it different from rest syntax?
  11. Explain the Prototype Design Pattern?
  12. What is the difference between .call and .apply?
  13. What are the actual uses of ES6 WeakMap?
  14. What is the difference between ES6 Map and WeakMap?
  15. How to “deep-freeze” object in JavaScript?
  16. What is the preferred syntax for defining enums in JavaScript?
  17. Explain the difference between Object.freeze() vs const?
  18. When are you not supposed to use the arrow functions in ES6? Name three or more cases.
  19. Can you give an example of a curry function, and why does this syntax have an advantage?
  20. What are the template literals in ES6?
  21. What do you understand by Generator function?

Below are the new features listed

  1. Constants (Immutable variables)
  2. Scoping
  3. Arrow functions
  4. Extended parameter handling
  5. Template literals
  6. Extended literals
  7. Modules
  8. Classes
  9. Enhanced Regular expressions
  10. Enhanced object properties.
  11. Destructuring Assignment
  12. Symbol Type
  13. Iterators
  14. Generator
  15. Map/Set & WeakMap/WeakSet
  16. Typed Arrays
  17. Built-in Methods
  18. Promises
  19. Meta programming
  20. Internationalization and Localization.

ECMAScript 5 (ES5):

The 5th edition of ECMAScript, standardized in 2009. This standard has been implemented fairly completely in all modern browsers

ECMAScript 6 (ES6)/ ECMAScript 2015 (ES2015):

The 6th edition of ECMAScript, standardized in 2015. This standard has been partially implemented in most modern browsers.

Here are some key differences between ES5 and ES6:

  1. Arrow functions & string interpolation:
     
      
        const greetings = (name) => {
            return `hello ${name}`;
        }
    
        const greetings = name => `hello ${name}`;   
      
    
  2. Const

    Const works like a constant in other languages in many ways but there are some caveats. Const stands for ‘constant reference’ to a value. So with const, you can actually mutate the properties of an object being referenced by the variable. You just can’t change the reference itself.

     
      
        const NAMES = [];
        NAMES.push("Jim");
        console.log(NAMES.length === 1); // true
        NAMES = ["Steve", "John"]; // error   
      
    
  3. Block-scoped variables

    The new ES6 keyword let allows developers to scope variables at the block level. Let doesn’t hoist in the same way var does.

  4. Default parameter values

    Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value

     
      
        // Basic syntax
        function multiply (a, b = 2) {
             return a * b;
        }
        multiply(5); // 10  
      
    
  5. Class Definition and Inheritance

    ES6 introduces language support for classes (class keyword), constructors (constructor keyword), and the extend keyword for inheritance.

  6. for-of operator

    The for…of statement creates a loop iterating over iterable objects

  7. Spread Operator

    For objects merging

     
      
        const obj1 = { a: 1, b: 2 }
        const obj2 = { a: 2, c: 3, d: 4}
        const obj3 = {...obj1, ...obj2}
      
    
  8. Promises

    Promises provide a mechanism to handle the results and errors from asynchronous operations. You can accomplish the same thing with callbacks, but promises provide improved readability via method chaining and succinct error handling.

     
      
        const isGreater = (a, b) => {
          return new Promise ((resolve, reject) => {
            if(a > b) {
              resolve(true)
            } else {
              reject(false)
            }
            })
        }
        isGreater(1, 2)
          .then(result => {
            console.log('greater')
          })
         .catch(result => {
            console.log('smaller')
         })
      
    
  9. Modules exporting & importing
     
      
        const myModule = { x: 1, y: () => { console.log('This is ES5') }}
        export default myModule;
      
    
     
      
        import myModule from './myModule';
      
    

These are APIs that are standard JavaScript APIs that help with different tasks such as collation, number formatting, currency formatting, date and time formatting.

  • Collation

    It is used to search within a set of strings and sort a set of strings. It is parametrized by the locale and Unicode-conscious.

  • Number Formatting

    Numbers can be formatted with localized separators and digit groupings. Other things that include style formatting, numbering, percent, and precision.

  • Currency formatting

    Numbers can be formatted mainly with currency symbols, with localized separators and digit groupings.

  • Date and time formatting

    It has been formatted and ordered with localized separators. The format can be short, long and other parameters, such as the locale and time zone.

It’s an Immediately Invoked Function Expression, or an IIFE for short. It will run immediately after it has been created:

	
	
		(function IIFE(){
		    console.log( "Hello!" );
		})();
		// "Hello!"		
	

This pattern is often used when trying to avoid contaminating the global namespace, because all variables used inside the IIFE (like any other normal function) are not visible outside its scope.

Top 21 Essential Java Developer Interview Questions

I am now using the following thumb rule for functions in ES6 and beyond:

  • Use function in the global scope and for Object.prototype properties.
  • Use class for object constructors.
  • Use => everywhere else.

Why use arrow functions almost everywhere?

  • Scope safety

    When arrow functions are used consistently, everything is guaranteed to use the same object as the root. If even a single standard function callback is mixed in with a bunch of arrow functions, there’s a chance that the scope will get messed up.

  • Compactness

    The Arrow functions are easier to read and write to. (This may seem to be an opinion, so I’m going to give a few more examples).

  • Clarity

    When almost everything is an arrow function, any regular function immediately sticks out to define the scope. The developer can always look up the next-higher function statement to see what the object is.

Let’s first look at example of each:

 
  
    // ES5 Function Constructor
    function Person(name) {
      this.name = name;
    }

    // ES6 Class
    class Person {
      constructor(name) {
        this.name = name;
      }
    }   
  

For simple constructors, they look pretty similar.

The main difference in the constructor comes when using inheritance. If we want to create a Student class that subclasses Person and add a studentId field, this is what we have to do in addition to the above.

 
  
    // ES5 Function Constructor
    function Student(name, studentId) {
      // Call constructor of superclass to initialize superclass-derived members.
      Person.call(this, name);

      // Initialize subclass's own members.
      this.studentId = studentId;
    }

    Student.prototype = Object.create(Person.prototype);
    Student.prototype.constructor = Student;

    // ES6 Class
    class Student extends Person {
      constructor(name, studentId) {
        super(name);
        this.studentId = studentId;
      }
    }   
  

Some of the reasons you might choose to use Classes:

  • Syntax is simpler and less error prone.
  • It’s much easier (and again, less error-prone) to set up inheritance hierarchies using the new syntax than the old one.
  • Class defends you from the common error of not using a new constructor function (by having the constructor throw an exception if this is not a valid constructor object).
  • Calling the parent prototype version of the method is much simpler with a new syntax than the old one (super.method() instead of ParentConstructor.prototype.method.call(this) or Object.getPrototypeOf(Object.getPrototypeOf(this)).

Consider:

 
  
    / **ES5**
    var Person = function(first, last) {
        if (!(this instanceof Person)) {
            throw new Error("Person is a constructor function, use new with it");
        }
        this.first = first;
        this.last = last;
    };

    Person.prototype.personMethod = function() {
        return "Result from personMethod: this.first = " + this.first + ", this.last = " + this.last;
    };

    var Employee = function(first, last, position) {
        if (!(this instanceof Employee)) {
            throw new Error("Employee is a constructor function, use new with it");
        }
        Person.call(this, first, last);
        this.position = position;
    };
    Employee.prototype = Object.create(Person.prototype);
    Employee.prototype.constructor = Employee;
    Employee.prototype.personMethod = function() {
        var result = Person.prototype.personMethod.call(this);
        return result + ", this.position = " + this.position;
    };
    Employee.prototype.employeeMethod = function() {
        // ...
    };  
  

In ES6 classes

 
  
    // ***ES2015+**
    class Person {
        constructor(first, last) {
            this.first = first;
            this.last = last;
        }

        personMethod() {
            // ...
        }
    }

    class Employee extends Person {
        constructor(first, last, position) {
            super(first, last);
            this.position = position;
        }

        employeeMethod() {
            // ...
        }
    } 
  

Hoisting is the action of the JavaScript interpreter to move all the variables and function declarations to the top of the current scope. There are two types of hoists:

  1. variable hoisting – rare
  2. function hoisting – more common

Where a var (or function declaration) appears within the scope of the declaration, it shall be taken to belong to the whole scope and shall be accessible everywhere.

	
	
		var a = 2;
		foo();                 // works because `foo()`
		                         // declaration is "hoisted"

		function foo() {
		    a = 3;
		    console.log( a );   // 3
		    var a;             // declaration is "hoisted"
		                         // to the top of `foo()`
		}

		console.log( a );   // 2
	

21 React JS Interview Questions and Answers

Symbols are a new, special type of object that can be used as a unique property name in objects. Using Symbol instead of string allows different modules to create properties that do not conflict with each other. Symbols can also be made private, so that no one who does not already have direct access to the Symbol can access their properties.

Symbols are a new primitive thing. Just like the number, string, and boolean primitives, the symbol has a function that can be used to create them. Unlike other primitives, the symbols do not have a literal syntax (e.g. how string have '') “-the only way to create them is with the symbol constructor in the following way:

	
	
		let symbol = Symbol();
	

In reality, Symbol's is just a slightly different way of attaching properties to an object-you could easily provide well-known Symbols as standard methods, just like Object.prototype.hasOwnProperty, which appears in everything that inherits from Object.

ES6 spread syntax is very useful when coding in a functional paradigm as you can easily create copies of arrays or objects without using Object.create, slice, or a library function. This language feature is often used in Redux and rx.js projects.

	
	
		function putDookieInAnyArray(arr) {
		  return [...arr, 'dookie'];
		}

		const result = putDookieInAnyArray(['I', 'really', "don't", 'like']); // ["I", "really", "don't", "like", "dookie"]

		const person = {
		  name: 'Todd',
		  age: 29,
		};

		const copyOfTodd = { ...person };
	

The rest syntax of ES6 offers a shorthand for including an arbitrary number of arguments to be passed to a function. It’s like the inverse of the spread syntax, taking data and stuffing it into an array rather than unpacking array of data, and it works in function arguments, as well as in array and object destructuring assignments.

	
	
		function addFiveToABunchOfNumbers(...numbers) {
		  return numbers.map(x => x + 5);
		}

		const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10); // [9, 10, 11, 12, 13, 14, 15]

		const [a, b, ...rest] = [1, 2, 3, 4]; // a: 1, b: 2, rest: [3, 4]

		const { e, f, ...others } = {
		  e: 1,
		  f: 2,
		  g: 3,
		  h: 4,
		}; // e: 1, f: 2, others: { g: 3, h: 4 }
	

The Prototype Pattern creates new objects, but instead of creating non-initialized objects, it returns objects that are initialized with values copied from a prototype-or sample-object. The pattern of the prototype is also referred to as the pattern of the properties.

An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values of the database. The prototype object holds the default values that are copied to the newly created business object.

Classical languages rarely use the Prototype pattern, but the JavaScript being a prototype language uses this pattern in the construction of new objects and their prototypes.

Both .call and .apply are used to invoke functions, and the first parameter will be used as the value of this within the function. However, .call takes the comma-separated arguments as the next arguments, while .apply uses the array of arguments as the next argument. An easy way to remember this is C for a call and a comma-separated and A for apply and an array of arguments.

	
	
		function add(a, b) {
		  return a + b;
		}

		console.log(add.call(null, 1, 2)); // 3
		console.log(add.apply(null, [1, 2])); // 3	
	

WeakMaps provide a way to extend objects from the outside without interference with garbage collection. Whenever you want to extend an object, but can’t apply a WeakMap because it is sealed-or from an external source.

WeakMaps provide a way to extend objects from the outside without interference with garbage collection. Whenever you want to extend an object, but can’t apply a WeakMap because it is sealed-or from an external source.

	
	
		var map = new WeakMap();
		var pavloHero = {
		    first: "Pavlo",
		    last: "Hero"
		};
		var gabrielFranco = {
		    first: "Gabriel",
		    last: "Franco"
		};
		map.set(pavloHero, "This is Hero");
		map.set(gabrielFranco, "This is Franco");
		console.log(map.get(pavloHero)); //This is Hero	
	

The interesting aspect of the WeakMaps is that it has a weak reference to the key inside the map. A weak reference means that if the object is destroyed, the garbage collector will remove the entire entry from the WeakMap, freeing up memory.

They both behave differently when the object referred to by their keys / values is deleted. Take the following example code:

var map = new Map();

var weakmap = new WeakMap();

	
	
		(function() {
		    var a = {
		        x: 12
		    };
		    var b = {
		        y: 12
		    };

		    map.set(a, 1);
		    weakmap.set(b, 2);
		})()
	

The above IIFE is executed there is no way we can refer to {x:12} and {y:12}. The Garbage Collector goes ahead and removes the “WeakMap” key b pointer and also removes {y:12} from memory. But in the case of “Map,” the garbage collector does not remove a pointer from “Map” and does not remove {x:12} from memory.

WeakMap allows the garbage collector to do his job, but not Map. With manually written maps, the key array would keep references to key objects, preventing them from being garbage collected. In native WeakMaps, references to key objects are kept “weakly” which means that they do not prevent the collection of garbage in the event that there is no other reference to the object.

If you want to make sure that the object is deep frozen, you need to create a recursive function to freeze each property that is of the object type:

Without deep freeze:
	
	
	let person = {
		name: "Leonardo",
		profession: {
			name: "developer"
		}
	};
	Object.freeze(person); // make object immutable
	person.profession.name = "doctor";
	console.log(person); //output { name: 'Leonardo', profession: { name: 'doctor' } }
	
With deep freeze:
	
	
	function deepFreeze(object) {
	    let propNames = Object.getOwnPropertyNames(object);
	    for (let name of propNames) {
	        let value = object[name];
	        object[name] = value && typeof value === "object" ?
	            deepFreeze(value) : value;
	    }
	    return Object.freeze(object);
	}
	let person = {
	    name: "Leonardo",
	    profession: {
	        name: "developer"
	    }
	};
	deepFreeze(person);
	person.profession.name = "doctor"; // TypeError: Cannot assign to read only property 'name' of object
	

Since 1.8.5 it’s possible to seal and freeze the object, so define the above as:

	
	
		const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})
	
Or
	
	
		const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
		Object.freeze(DaysEnum);
	

and voila! JS enums.

However, this does not prevent you from assigning an undesired value to a variable, which is often the main goal of the enums:

	
	
	let day = DaysEnum.tuesday
	day = 298832342 // goes through without any errors
	

Since its release, ES6 has introduced several new features and methods to JavaScript. Among these new features are the method and const of Object.freeze(). Sometimes people get confused between the method Object.freeze() and the const but Object.freeze() and the const are completely different.

Const:

The const keyword generates a read-only reference to a value. The variables generated by the const keyword are immutable. In other words, you can’t reassign them to a variety of values. Trying to reassign a constant variable will result in a TypeError.

	
	
		let myName = "indiahires"
	    console.log(myName)  
	  
	    // Uncaught TypeError 
	    myName = "ih" 
	

The const keyword ensures that the created variable is read-only. But it doesn’t mean that the actual value to which the reference to the const variable is immutable. Even though the variable person is constant. However, you can change the value of your property. But you can not reassign a different value to a constant person.

	
	
		const person = { 
	        name: "indiahires"
	    }; 
	          
	// No TypeError 
	person.name = "ih"; 
	console.log(person.name);  
	
Object.freeze() method:

If you want the value of the person object to be immutable, you have to freeze it using the Object.freeze() method.

	
	
	const person = Object.freeze({name: "indiahires"});      
     // TypeError 
     person.name = "ih";  
	

The method Object.freeze() is shallow, which means that it can freeze the properties of the object, not the objects referenced by the properties.

	
	
	const person = Object.freeze({ 
	    name: 'indiahires', 
	    address: { 
	        city:"Chandigarh"
	    } 
	});  

	/*But the person.address object is not immutable, you can add a new property to the person.address object as follows:*/

	// No TypeError
	person.address.country = "India";
	
Final words

const prevents reassignment.

Object.freeze() prevents mutability.

Arrow functions should NOT be used:

  1. When we want function hoisting – as arrow functions are anonymous.
  2. When we want to use this/arguments in a function – as arrow functions do not have this/arguments of their own, they depend upon their outer context.
  3. When we want to use named function – as arrow functions are anonymous.
  4. When we want to use function as a constructor – as arrow functions do not have their own this.
  5. When we want to add function as a property in object literal and use object in it – as we can not access this (which should be object itself).

Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, accumulates all the required parameters one at a time. This technique can be useful to make it easier to read and compose code written in a functional style. It is important to note that if a function is to be cured, it needs to start as a single function, and then break out into a sequence of functions, each of which accepts a single parameter.

There is a lot of mathematical and computer science theory behind currying in functional programming and I encourage you to read more on Wikipedia. Interesting fact: Currying is named after a mathematician Haskell Curry, not the food.

Basic example:

	
	
		const sum = x => y => x + y;
		// returns the number 3
		sum (2)(1);
		// returns a function y => 2 + y
		sum (2);	
	

Note that sum (2)(1); produces the same result as we would have had if we had defined it as const sum = (x , y) = > x + y; which we would call const sum = (x , y) = > x + y; Summary (2 , 1);.

If seeing more than one arrow gives you trouble, just realize that you are simply returning everything that is behind the first arrow. In this case it’s returning another function as its return value because JavaScript has first-class functions. Also this approach works, because the nested returned function has access to the scope of its parent function and so conveniently the y => x + y gets the x from its parent.

First class functions

in functional programming JavaScript has first class functions because it supports functions as arguments and return values.

	
	
		const someFunction = () => console.log ('Hello World!');
		const firstClass1 = functionAsArgument => functionAsArgument ();

		firstClass1(someFunction); // Hello World! is printed out

		const firstClass2 = () => someFunction;

		firstClass1 (firstClass2()); // Hello World! is printed out	
	

Practical example: curry as a partial application

This is an example of partially applied function versus curry function, both doing the same thing using JQuery “on” function:

	
	
		const partiallyAppliedOnClick = handler => $ ('button').on ('click', handler);

		const curryOn = handler => event => $ ('button').on (event, handler);

		const curryOnClick = handler => curryOn (handler) ('click');
	

Curry functions are neat when used for carrying reusable code containers. You take a function with multiple arguments, and you know that one of those arguments will have a specific value, but the other is undecided. Therefore, by using curry as a fancy partial application, you can create a new function that will allow you to deal with undecided arguments only without repeating your code.

Practical example: curry for functional composition

Functional composition is a concept that is worthy of its own post. The problem we’re trying to solve by currying is that JavaScript is full of object-oriented approaches that can be difficult to use with functional code, especially if you want to be a purist (or a hipster) about it.

In functional composition you have a sequence of functions applied all on the same single argument as f(g(x)). This would be your example:

	
	
		// Object oriented approach
		const getUglyFirstCharacterAsLower = str
		  => str.substr (0, 1).toLowerCase ();

		// Functional approach
		const curriedSubstring = start => length => str
		  => str.substr(start, length);

		const curriedLowerCase = str => str.toLowerCase ();

		const getComposedFirstCharacterAsLower = str
		  => curriedLowerCase (curriedSubstring (0) (1) (str));
	

It is also very popular to use a compose function to compose your functions:

	
	
		const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
	

Using the above-defined functions curriedSubstring and curriedLowerCase you can then use compose to do this:

	
	
		const getNewComposedFirstCharacterAsLower = compose (curriedLowerCase, curriedSubstring (0) (1));
		if (getComposedFirstCharacterAsLower ('Martin') === getNewComposedFirstCharacterAsLower ('Martin') {
		  console.log ('These two provide equal results.');
		}
	
	
	
		function curry(fn) {
		  if (fn.length === 0) {
		    return fn;
		  }

		  function _curried(depth, args) {
		    return function(newArgument) {
		      if (depth - 1 === 0) {
		        return fn(...args, newArgument);
		      }
		      return _curried(depth - 1, [...args, newArgument]);
		    };
		  }

		  return _curried(fn.length, []);
		}

		function add(a, b) {
		  return a + b;
		}

		var curriedAdd = curry(add);
		var addFive = curriedAdd(5);

		var result = [0, 1, 2, 3, 4, 5].map(addFive); // [5, 6, 7, 8, 9, 10]
	

Source: JavaScript ES6 curry functions with practical examples

The literal template is a new feature introduced in ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals allow embedded expressions, also called literal strings.

Previous to ES6, literal templates were referred to as template strings. The literal template is enclosed with the backtick (` x`) character. Placeholders in the literal template are represented by the dollar sign and the curly braces (${expression}). If we need to use the expression in the backticks, we can place the expression in (${expression}).

Basic example:

	
	
		let str1 = "Hello";  
  
		let str2 = "World";  
		   
		let str = `${str1} ${str2}`;  
		console.log(str);  	
	

A generator gives us a new way to work with iterators and functions. The generator is a special type of function that can be paused one or more times in the middle and can be resumed later. The function declaration * (function keyword followed by an asterisk) is used to define a generator function.

When the generator is called, the code does not run. Instead, it returns a special object that is called the Generator object to manage the execution. Let’s look at the example of generators in ES6.

To learn more about Generators in ES6, follow this link ES6 Generators.

Basic example:

	
	
		function* gen() {    
			yield 100;    
			yield;    
			yield 200;    
		}    
		// Calling the Generator Function    
		var mygen = gen();    
		console.log(mygen.next().value);    
		console.log(mygen.next().value);    
		console.log(mygen.next().value);     	

		//Output

		100
		undefined
		200
	

Both for..of and for..in statements iterate across lists; the values iterated on are different though, for..in returns a list of keys to the object being iterated, while for..of returns a list of values of the numeric properties of the object being iterated.

Here is an example that demonstrates this distinction:

	
	
		let list = [4, 5, 6];

		for (let i in list) {
		   console.log(i); // "0", "1", "2",
		}

		for (let i of list) {
		   console.log(i); // "4", "5", "6"
		}
	

Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

	
	
		let pets = new Set(["Cat", "Dog", "Hamster"]);
		pets["species"] = "mammals";

		for (let pet in pets) {
		   console.log(pet); // "species"
		}

		for (let pet of pets) {
		    console.log(pet); // "Cat", "Dog", "Hamster"
		}
	

Although this has been a pretty long article to follow through, I strongly believe that most of us must have learned what kind of ES6 interview questions asked in the interview.

ES6 Basic Interview Questions

1. Mention some popular features of ES6.

Some of the common ES6 features are:

  • Supports constants/immutable variables.
  • Block scope support for all variables, constants and functions.
  • Introduction to arrow functions
  • Handling extended parameter
  • Default parameters
  • Extended and template literals
  • De-structuring assignment
  • Promises
  • Classes
  • Modules
  • Collections
  • Supports Map/Set & Weak-map/Weak-Set
  • Localization, meta-programming, internationalization

2. What are the object oriented features supported in ES6.

The object-oriented features supported in ES6 are:

  • Classes: We can create classes in ES6. The class function essentially builds a template from which we may later create objects. When a new instance of the class is created, the constructor method is invoked.
  • Methods: Static methods can also be found in classes. A static method, unlike an object, is a function that is bound to the class. A static method can’t be called from a class instance.
    Let’s take a look at getters and setters for a moment. Encapsulation is a fundamental notion in OOP. Data (object properties) should not be directly accessed or updated from outside the object, which is a crucial aspect of encapsulation. A getter (access) or a setter (modify) are particular methods we define in our class to access or edit a property.
  • Inheritance: It is also possible for classes to inherit from one another. The parent is the class that is being inherited from, and the child is the class that is inheriting from the parent.
     

3. Give a thorough comparison between ES5 and ES6.

ES5ES6
ES5 is the fifth edition of the ECMAScript which was introduced in 2009.ES6 is the sixth edition of the ECMAScript which was introduced in 2015.
Primitive data types that are string, boolean, number, null, and undefined are supported by ES5.There are a few additions to the JavaScript data types in ES6.  For supporting unique values, a new primitive data type ‘symbol’ was introduced.
In ES5, we could define the variables by using the var keyword only.In ES6, in addition to var, there are two new methods to define variables: let and const.
Both function and return keywords are used in order to define a function in ES5.An arrow function is a newly added feature in ES6 in which we don’t require the function keyword in order to define the function.
In ES5, a for loop is used to iterate over elements.ES6 introduced the idea of for…of loop in order to iterate over the values of the iterable objects.

4. What is the difference between let and const? What distinguishes both from var?

When declaring any variable in JavaScript, we used the var keyword. Var is a function scoped keyword. Within a function, we can access the variable. When we need to create a new scope, we wrap the code in a function.

Both let and const have block scope. If you use these keywords to declare a variable, it will only exist within the innermost block that surrounds them. If you declare a variable with let inside a block (for example, if a condition or a for-loop), it can only be accessed within that block.

The variables declared with the let keyword are mutable, which means that their values can be changed. It’s akin to the var keyword, but with the added benefit of block scoping. The variables declared with the const keyword are block-scoped and immutable. When variables are declared with the const keyword, their value cannot be modified or reassigned.

5. Discuss the arrow function.

In ES6, arrow functions are introduced. The shorthand syntax for writing ES6 functions is arrow functions. The arrow function’s definition consists of parameters, followed by an arrow (=>), and the function’s body.

The ‘fat arrow’ function is another name for the Arrow function. We won’t be able to employ them as constructors.

 const function_name = (arg_1, arg_2, arg_3, ...) => {  
    //body of the function  
} 

Few things to note:

  • It reduces the size of the code.
  • For a single-line function, the return statement is optional.
  • Bind the context lexically.
  • For a single-line statement, functional braces are not required.
  • Doesn’t work with new

6. When should one not use arrow functions?

One should not use arrow functions in the following cases:

  • Function Hoisting, Named Functions:

As arrow functions are anonymous, we cannot use them when we want function hoisting or when we want to use named functions.

  • Object methods:
 var a = {
  b: 7,
  func: () => {
    this.b--;
  }
}

The value of b does not drop when you call a.func. It’s because this isn’t bound to anything and will inherit the value from its parent scope.

  • Callback functions with dynamic context:
 var btn = document.getElementById('clickMe');
btn.addEventListener('click', () => {
  this.classList.toggle('on');
});

We’d get a TypeError if we clicked the button. This is due to the fact that this is not bound to the button, but rather to its parent scope.

  • this/arguments:

Since arrow functions don’t have this/arguments of their own and they depend on their outer context, we cannot use them in cases where we need to use this/arguments in a function.

7. What is the generator function?

This is a newly introduced feature in ES6. The Generator function returns an object after generating several values over time. We can iterate over this object and extract values from the function one by one. A generator function returns an iterable object when called. In ES6, we use the * sign for a generator function along with the new ‘yield’ keyword.

 function *Numbers() {
    let num = 1;
    while(true) {
        yield num++;
    }
}
  
var gen = Numbers();
 
// Loop to print the first
// 5 Generated numbers
for (var i = 0; i < 5; i++) {
 
    // Generate the next number
    document.write(gen.next().value);
 
    // New Line
    document.write("<br>");
}

Output:

1
2
3
4
5

The yielded value becomes the next value in the sequence each time yield is invoked. Also, generators compute their output values on demand, allowing them to efficiently represent expensive to compute sequences or even infinite sequences.

8. What is the “spread” operator in ES6?

The list of parameters is obtained using the spread operator. Three dots (…) are used to represent it. The spread operator divides an iterable (such as an array or a string) into individual elements. It’s mostly used in JavaScript to make shallow copies of JS. It improves the readability of your code by making it more concise.

The spread operator can be used to join two arrays together or to concatenate them.

let arr1 = [4, 5, 6];  
    
let arr2 = [1, 2, 3, ...arr1, 7, 8, 9, 10];  
    
console.log(arr2);

Output:

[ 1 2 3 4 5 6 7 8 9 10 ]

9. Explain Destructuring in ES6.

Destructuring was introduced in ES6 as a way to extract data from arrays and objects into a single variable. It is possible to extract smaller fragments from objects and arrays using this method. The following is an example.

let greeting =['Good','Morning'];  
let [g1, g2] = greeting;  
console.log (g1, g2);

Output:

Good Morning

10. What are Promises in ES6?

Asynchronous programming is a concept found in JavaScript. The processes are run separately from the main thread in asynchronous programming. Promises are the most convenient approach to deal with asynchronous programming in ES6. Depending on the outcome of the procedure, a promise can be refused or resolved. Callbacks were used to cope with asynchronous programming before promises were introduced in ES6.

However, it caused the problem of callback hell, which was addressed with the introduction of promises.

(A callback is a function that is performed after another function has completed. When working with events in JavaScript, callback is very useful. As an argument to another function, we pass a function into another function.

When we use callbacks in our web applications, it’s common for them to get nested. Excessive callback usage clogs up your web application and leads to callback hell.)

11. Explain the Rest parameter in ES6.

It’s a new feature in ES6 that enhances the ability to manage arguments. Indefinite arguments can be represented as an array using rest parameters. We can invoke a function with any number of parameters by utilizing the rest parameter.

 function display(...args) {  
    let ans = 0;  
    for (let i of args) {  
        ans *= i;  
    }  
    console.log("Product = "+ans);  
  }  
    
  display(4, 2, 3); 

Output:

 Product = 24

12. Discuss the template literals in ES6.

Template literals are a brand-new feature in ES6. It makes producing multiline strings and performing string interpolation simple.

Template literals, also known as string literals, allow for embedded expressions.

Template literals were referred to as template strings prior to ES6. The backtick (“) character is used to enclose template literals. The dollar sign and curly brackets (${expression}) are used to denote placeholders in template literals. If we need to use an expression within the backticks, we can put it in the (${expression}) variable.

let s1 = "Good";  
  
let s2 = "Day";  
   
let s = `${s1} ${s2}`;  
console.log(s);  

Output:

 Good Day

13. Why should one use ES6 classes?

Developers have discovered that ES6 classes are really handy. The following are some of the most common applications of ES6 classes:

  • The syntax of ES6 classes is simpler and less prone to errors.
  • When it comes to building up inheritance hierarchies, ES6 is the ideal option because it combines new and old syntax, reducing errors and simplifying the process.
  • ES6 classes prevent developers from making mistakes when using a new operator. If this proves to be an invalid object for the constructor, classes eliminate this issue by having the constructor throw an exception.
  • Classes can also be used to call a method from the prototype’s version. With the new ES6 syntax, this version is significantly easier to use than previous versions.

14. How can you create a class in ES6?

The keyword class is used to create a class in ES6. We can use class expressions or class declarations to include classes in our code. Only functions and constructors are allowed in a class definition. These components are collectively referred to as the class’s data members.

Constructors in classes are responsible for allocating memory to the class’s objects. A class’s functions are in charge of performing actions on the objects.

Syntax: In ES5

 var varName = new className {    
}  

Syntax: In ES6 (Using class keyword)

 class className{    
}   

15. What is a class expression?

In ES6, one way to define a class is to use the Class expression. Class expressions, like function expressions, can be named or unnamed. If the class is named, the name is unique to the class body. Prototype-based inheritance is used in JavaScript classes.

 var Product = class {
    constructor (num1, num2) {
    this.num1 = num1;
    this.num2 = num2;
    }
    multiplication() {
    return this.num1 * this.num2;
    }
}
console.log(new Product(5,8).multiplication());
// expected output: 40

The syntax of a class expression is similar to that of a class statement (declaration). Class expressions, on the other hand, allow you to omit the class name (“binding identifier”), which is not possible with class statements. Additionally, unlike class declarations, class expressions allow you to redefine/re-declare classes without causing any type errors. It is not required to use the constructor property. The type of classes created with this keyword will always be “function.”

16. What do you understand about default parameters?

If no value or undefined is passed, we can use the default parameters to set default values for named parameters.

 var display = (x , y = 2) => {  
    console.log(x + " " + y);  
}  
display(1);  

Output:

 1 2

17. What do you understand about IIFE (Immediately Invoked Function Expressions)?

 IIFE is a JavaScript function that starts running as soon as it is defined. The Self-Executing Anonymous Function is another name for it. It is divided into two major sections, which are as follows:

  • The first part is a lexical scope (static scope) anonymous function that is enclosed by the Grouping operator ().
  • The IIFE, which is used by JavaScript, is created in the second part. The function will be directly interpreted by the engine.
 (func_()    
{    
   console.log("Good Day");     
})();    

Output:

 Good Day

18. What are the states of Promises in ES6?

Promises mainly possess three states as follows:

  • Pending: This refers to the initial state of every promise. It indicates that the result has not yet been computed.
  • Fulfilled: It refers to the completion of a task.
  • Rejected: It indicates the failure that arises during computation.

The promise will be immutable once it has been fulfilled or rejected. A rejected function and a resolve function are the two arguments passed into the Promise() constructor. It returns either the first or second parameter, depending on the asynchronous operation.

19. What is Export Default and Named Export in ES6?

With the help of the import statement, the export statement comes into picture when one needs to export functions, objects, and variables to other JavaScript modules. There are two methods for exporting:

  • Named Export: Named exports are useful when one has to export multiple values. The name of the imported module must match that of the exported module.

Example:

 //file rectangle.js
function perimeter(x, y) {
  return 2 * (x + y);
}
function area(x, y) {
  return x * y;
}
export { perimeter, area };
  
   
//while importing the functions in test.js
import { perimeter, area } from './rectangle;
console.log(perimeter(4, 6)) //20
console.log(area(4, 6)) //24

Output:

20
24
  • Default Export: There is only one default export per module when it comes to default exports. A function, a class, an object, or anything else can be used as a default export. In default export, the naming of imports is fully autonomous, and we can choose any name we like.

Example:

 // file module.js
var a = 6; 
export default a;
  
// test.js
// while importing a in test.js
import b from './module'; 
console.log(b);        
// output will be 6

Output:

 6
  • Using Named and Default Exports at the same time: In the same file, you can utilise both Named and Default exports. It means they’ll both be imported into the same document.
 //index.js
var a = 3;
const b = 8;
function show() {
   return "This is a default export."
}
function product(a , b) {
  return a * b;
}
export { show as default, a, b, product };
//test.js file
import any_other_name, { a, b, product} from './index.js';
console.log(any_other_name()); //This is a default export.
console.log(a); //3

Output:

This is a default export.
3

20. Which keyword can be used to deploy inheritance in ES6?

The extend keyword is used to implement inheritance in the ES6 language. There was no idea of classes in prior versions of Javascript, but with the release of ES6, Pure Object Oriented elements were added to the language.

 class Classroom {
    constructor(students) {
        this.students = students;
    }
    room() {
        console.log('This class has  ' + this.students + ' students');
    }
}
 
class sectionA extends Classroom {
    constructor(students) {
        super(students);
    }
    sec() {
        console.log('section A');
    }
}
  
let secA = new sectionA(40);
 
secA.room();
secA.sec();

21. What is Bubbling and Capturing?

When an event occurs on the DOM, it does not take place completely on one element. The event bubbles up or goes to its parent, grandparents, and grandparent’s parent until it reaches the window in the Bubbling Phase, whereas the event starts out from window down to the element that prompted the event or the event target in the Capturing Phase.

There are three stages of event propagation:

  • Capturing Phase – the event begins with the window and progresses through each element until it reaches the target element.
  • Target Phase – The event has arrived at the target element.
  • Bubbling Phase – The event bubbles up from the target element and then up every element until it reaches the window.

22. What is the difference between for..of and for..in?

  • for in: runs over an object’s enumerable property names.
  • for of: (new in ES6) takes an object-specific iterator and loops through the data it generates.

Both the for..of and for..in commands iterate over lists, but the results they return are different: for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the object’s numeric attributes.

let arr = [3, 4, 5];

for (let i in arr) {
   console.log(i); // "0", "1", "2",
}

for (let i of arr) {
   console.log(i); // "3", "4", "5"
}

23. What is the reason behind adding Symbol to ES6?

Symbols are a new type of object that can be used as distinct property names in objects. Using Symbols instead of strings allows separate modules to create properties that are not mutually exclusive. Symbols can also be kept private, preventing anyone who does not have direct access to the Symbol from accessing its properties.

Symbols are a brand-new kind of primitive. Symbols, like numbers, strings, and booleans, have a function that can be used to produce them. Symbols, unlike the other primitives, do not have a literal syntax (similar to how strings have “) and can only be created using the Symbol constructor:

 let symbol = Symbol();

In truth, Symbols are only a little different means of attaching properties to an object; the well-known Symbols could easily be provided as standard methods, just like Object.prototype.has Own Property which appears in anything that inherits from Object.

24. What is Babel?

Babel is an open-source JavaScript transpiler that converts ECMAScript 2015+ (ES6+) code into a backwards compatible version of JavaScript that can be run by previous JavaScript engines. Babel is a popular tool for exploiting the JavaScript programming language’s latest capabilities. 

Babel plugins are used to convert syntax that isn’t widely supported into a version that is backwards compatible. Arrow functions, for example, which are defined in ES6, are translated to ordinary function declarations. It’s also possible to translate non-standard JavaScript syntax, such as JSX. Babel may automatically inject core-js polyfills for support capabilities that aren’t available in JavaScript environments. Static methods like Array.from and built-ins like Promise, for example, are only accessible in ES6+, but they can be utilised in previous contexts by using core-js.

25. Name some array methods that were introduced in ES6.

MethodsDescription
Array.from()It will convert iterable values and array-like values into arrays.
Array.of()It will create a new array instance from a variable number of arguments no matter what the number or the type of arguments are.
Array.prototype.copyWithin()It will copy the portion of an array to a different place within the same array.
Array.prototype.find()It will find an element in an array, based on certain parameters that are passed into this method.
Array.prototype.findIndex()It will return the index of the first element of the given array that fulfills the given condition.
Array.prototype.entries()It will return an array iterator object that can be used while looping through the keys and values of arrays.
Array.prototype.keys()It will return an array iterator object as well as the keys of the array.
Array.prototype.values()It will provide the value of each key.
Array.prototype.fill()It will fill the specific array elements with a static value.

26. Name some string functions introduced in ES6.

MethodsDescription
startsWithIt determines if a string begins with the characters of a given string.
endsWithIt determines if a string ends with the characters of a given string.
includesIt will return true if the given argument is present in the string.
repeatIt creates and returns a new string which contains the given number of copies of the string on which this method was called, concatenated together.

27. Compare the ES5 and ES6 codes for object initialization and parsing returned objects.

Object initialization: Variables with the same name are frequently used to create object properties. Consider the following scenario:

 // ES5 code
var
  x = 1, y = 2, z = 3;
  ob = {
    x : a,
    y : b,
    z : z
  };

// ob.x = 1, ob.y = 2, ob.z = 3

In ES6, there’s no need for tedious repetition!

 // ES6 code
const
  x = 1, y = 2, z = 3;
  ob = {
    x
    y
    z
  };

// ob.x = 1, ob.y = 2, ob.z = 3

Parsing returned objects: Only one value can be returned by a function, but that value could be an object with hundreds of properties and/or methods. In ES5, you must first get the returned object and then extract values from it. Consider the following scenario:

 // ES5 code
var
  ob = getObject(),
  a = ob.a,
  b = ob.b,
  c = ob.c;

This is made easier by ES6 destructuring, which eliminates the need to keep the object as a variable:

 // ES6 code
const { a , b , c } = getObject();

28. How do you use Destructuring Assignment to swap variables?

var a = 1, b = 2;

[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1

29. What is the result of the spread operator array shown below?

[...'apple']

Output: [‘a’, ‘p’, ‘p’, ‘l’, ‘e’]

Explanation: A string is an iterable type, and in an array, the spread operator transfers each character of an iterable to one element. As a result, each character in a string becomes an Array element.

ES6 Interview Questions for Experienced

30. What is the Prototype Design Pattern?

The Prototype Pattern creates new objects, but instead of returning uninitialized objects, it returns objects with values copied from a prototype – or sample – object. The Properties pattern is another name for the Prototype pattern.

The initialization of business objects with values that match the database’s default settings is an example of where the Prototype pattern comes in handy. The default values from the prototype object are replicated into a newly generated business object.

The Prototype pattern is rarely used in traditional languages, but JavaScript, as a prototypal language, employs it in the creation of new objects and prototypes.

31. What is a WeakMap in ES6? How is it different from a Map?

The WeakMap is a collection of key/value pairs, just like the Map. The keys of WeakMap, on the other hand, must be objects, whereas the values can be anything. The object references in the keys are held weakly, which means that if there is no other reference to the object, it will be eligible for garbage collection. WeakMap, but not Map, permits the garbage collector to complete its duty. The array of keys would preserve references to key objects in manually constructed maps, prohibiting them from being garbage collected. References to key objects in native WeakMaps are held “weakly,” which means they do not hinder garbage collection if there is no other reference to the object. The Map API and the WeakMap API are the same.

WeakMap keys, on the other hand, are not enumerable, unlike Map objects. There are also no methods that return a list of keys. If they were, the list would be non-deterministic because it would be dependent on the state of garbage collection. A Map should be used if we need a list of keys.

32. What is the advantage of using the arrow syntax for a constructor method?

The main benefit of utilising an arrow function as a method within a constructor is that the value of this is set at the moment of function generation and cannot be changed later. As a result, whenever the constructor is used to create a new object, this refers to that object.

 const Shape = function(shapeName) {
  this.shapeName = shapeName;
  this.showName1 = function() { console.log(this.shapeName); };
  this.showName2 = () => { console.log(this.shapeName); };
};

const circle = new Shape('Circle');
const square = new Shape('Square');

circle.showName1(); // Circle
circle.showName2(); // Square

// The regular function can have its 'this' value changed, but the arrow function cannot
circle.showName1.call(square); // Square (because "this" is now the square object)
circle.showName2.call(square); // Circle

circle.showName1.apply(square); // Square (because 'this' is now the square object)
circle.showName2.apply(square); // Circle

circle.showName1.bind(square)(); // Square (because 'this' is now the square object)
circle.showName2.bind(square)(); // Circle

var showNameFromPic1 = circle.showName1;
sayNameFromPic1(); // undefined (because 'this' is now the pic object)

var showNameFromPic2 = circle.showName2;
showNameFromPic2(); // Circle

The major point here is that for a normal function, this can be modified, but for an arrow function, the context is always the same. You won’t have to worry about the context changing if you pass your arrow function around to other areas of your application.

33. What is a Temporal Dead Zone?

Variable Hoisting does not apply to let bindings in ES6, so let declarations do not rise to the top of the current execution context. A ReferenceError is thrown if the variable in the block is referenced before it is initialized (unlike a variable declared with var, which will just possess the undefined value). From the beginning of the block until the initialization is performed, the variable is in a “temporal dead zone.”

console.log(a); // undefined
console.log(b); // causes ReferenceError: aLet is not defined
var a = 1;
let b = 2;

34. What is the difference between Set and WeakSet in ES6?

Set: By using the Set() class, users can define an array-like heterogeneous iterable object, which will consist of distinct values. The elements should not just be distinct by values but also by types. i.e. “2” and 2 will be considered as different.

var set1= new Set([0, 1, 2]);

set1.add(3); // 0, 1, 2, 3
set1.add(2); // 0, 1, 2, 3
set1.add({x:1, y:2}); // 0, 1, 2, {x:1, y:2}
set1.add("Good"); // 0, 1, 2, {x:1, y:2}, 'Good'
 
set1.has("Hello"); // false
set1.has("Good");  // true
set1.delete("Good"); // 'Good' deleted
set1.has("Good"); // false
 
set1.size; // 4
set1.clear(); // Set Cleared

WeakSet(): A WeakSet() is a collection that is similar to a Set because it retains unique values; but it can only hold Objects. If an object in your WeakSet has no other reference variables left, it will be removed automatically.

 var weakSet1 = new WeakSet([{x:1}]);
var ob1 = {o:1};
var ob2 = {o:2};

weakSet1.has(ob1); //false
weakSet1.add(ob1); 
weakSet1.add(ob2); 
weakSet1.has(ob2); // true
delete ob1; // you can't delete objects in this way. Use scope to execute this.
myWeakSet.has(ob1); // false, because you deleted ob1, so WeakSet releases it automatically
myWeakSet.delete(ob2); // ob2 deleted from the set
myWeakSet.add(1); // ERROR, no primitive value
SetWeakSet
A set can contain all types of values.A weakSet can only contain objects.
Use .size to find the number of elements.Use .length to find the number of elements.
.forEach() is available for iteration..forEach() is not available for iteration.
Nothing is auto-destroyed.An element object will be auto released to the garbage collector if it has no other reference left.

35. What are Proxy in ES6?

The proxy objects are used to customize behaviour for basic operations like property lookup, assignment, enumeration, function invocation, etc.

For basic actions, the Proxy object is used to create custom behaviour (e.g. property lookup, assignment, enumeration, function invocation, etc).

We need to define three crucial terms:

  • handler —  a placeholder object that holds the trap(s)
  • traps — the method(s) that let you access a property.
  • target — the virtualized object by the proxy

Example:

 const handle = {
  get: function(ob, prp) {
    return prp in ob ?
      ob[prp] :
      37;
  }
};

const x = new Proxy({}, handle);
x.a = 2;
x.b = undefined;

console.log(x.a, x.b); 
//  2, undefined

console.log('c' in x, x.c); 
//  false, 37

Proxies have a wide range of real-world applications.

  • validation
  • correction in value
  • extensions for property lookup
  • property accesses are being tracked
  • references that can be revoked
  • implementation of the DOM in javascript

36. What is the difference between const and Object.freeze().

Const is a property that applies to bindings (“variables”). It creates an immutable binding, which means you can’t change its value.

 const a = {
    b: "apple"
};
let c = {
    d: "mango"
};
a = c; // ERROR "a" is read-only

Object.freeze() is a function that works with values, primarily object values. It makes an object immutable, meaning that its properties cannot be changed.

freeze() returns the same object that was supplied to it as a parameter. It does not make a frozen copy. If the parameter to this method is not an object (a primitive) in ES5, a TypeError will occur. A non-object argument in ES6 will be treated as if it were a frozen regular object and will be returned.

 let a = {
    b: "apple"
};
let c = {
    d: "mango"
};
Object.freeze(a);
a.b = "kiwi"; //TypeError: Cannot assign to read only property 'name' of object
console.log(a);

37. Why does the following not work as an IIFE (Immediately Invoked Function Expressions) ? What needs to be modified in order for it to be classified as an IIFE?

function f(){ }();

The JavaScript parser interprets the function f(){ }(); as function f(){ } and (); where the former is a function declaration while the latter (a pair of brackets) is an attempt to execute a function without specifying a name, resulting in Uncaught SyntaxError: Unexpected token ).

(function f(){ })() and (function f(){ }()) are two ways to fix it that involve adding more brackets. These functions are not available in the global scope, and you can even omit their names if you don’t need to refer to them within the body.

You can also use the void operator: void function f(){ }(); .However, there is a drawback in this strategy. Because the evaluation of a given expression is always undefined, you can’t use your IIFE function if it returns anything. Consider the following scenario:

 // Don't add JS syntax to this code block to prevent Prettier from formatting it.
const f = void
function b() {
    return 'f';
}();

console.log(f); // undefined

38. Explain Internationalization and Localization.

These are JavaScript standard APIs that assist with operations such as collation, number formatting, currency formatting, and date and time formatting.

  • Collation: It is a method for searching and sorting strings within a collection. It has a locale argument and is Unicode-aware.
  • Number Formatting: Localized separators and digit grouping can be used to format numbers. Style formatting, numeral system, percent, and precision are among the other items.
  • Currency formatting: Currency symbols, localized separators, and digit grouping are the most common ways to format numbers.
  • Date and time formatting: Localized separators and ordering are used for formatting. The format can be short or long, and other characteristics such as location and time zone can be included.

39. What is Webpack?

Webpack is a tool for bundling javascript files for usage in browsers. Webpack analyses the application and generates the bundles by creating a dependency graph that maps each module of the project required. It enables you to execute the environment that was hosted by Babel. A web pack has the advantage of combining numerous modules and packs into a single JavaScript file. It includes a dev server, which aids with code updates and asset management.

Write your code:

folder_name/index.js

 import bar from './func.js';
func();

folder_name/func.js

 export default function func() {
  // body of the function
}

Bundle it:

Either provide with custom webpack.config.js or without config:

 const path = require('path');

module.exports = {
  entry: './folder_name/index.js',
  output: {
    path: path.resolve(__dirname, 'dict'),
    filename: 'bundle.js',
  },
};

page.html

 <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    ...
  </head>
  <body>
    ...
    <script src="dict/bundle.js"></script>
  </body>
</html>

You, then, need to run the webpack on the command-line in order to create bundle.js.

MCQ on ES6

1.

Which of the following statements is false as regards this example?

 const ob = {
  outer: function() {
    const s1 = this

    const inner1 = () => {
      const s2 = this

      const inner2 = () => {
        const s3 = this
      }
    }
  }
}

s1 === s3s2 === s3s1 === s2s2 !== s32.

What will be the final value of the array below?

const arr = [10, 20, 30]
const ext = [40, 50, 60]

array = [...ext, ...arr]

[10, 20, 30][10, 20, 30, 40, 50, 60][40, 50, 60, 10, 20, 30][40, 50, 60]3.

What will be the final value of obj in the following case?

const obj = { foo: 2 }

obj.bar = 1

{ foo: 2 }the above throws an error{ foo: 2, bar: 1 }{ foo: 2, 1: bar }4.

What results will these function calls return?

 function sum(a=11, b=6) {
   return a+b;
}
// A
sum( 11, 2);
// B
sum(3);
// C
sum(undefined, 20);
// D
sum();

A – 17, B – 14, C – 31, D – 17A – 13, B – 9, C – 31, D – 17A – 13, B – 14, C – 31, D – undefinedA – 13, B – 9, C – undefined, D – undefined5.

Can you guess what the mysterious “x” variable holds?

 function mystery(...params) {
   return params;
}
let x = mystery(1, 2, 4);

“x” becomes “1 2 4″”x” becomes [1, 2, 4]”x” is undefined”x” becomes “1, 2, 4”6.

What is the output of the code given below?

 function* someGenerator({
   var n = 0;
   for(let i=0;i<10;i++){
     yield n++;
   }
}
var g = someGenerator();
g.next();
g.next();
console.log(g.next().value); // What will be printed here?

-12100107.

What should be the values of A and B?

 let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // expected output: A
}

console.log(x);
// expected output: B

A = 2, B = 1A = 2, B = 2A = 1, B = 2A = 1, B = 18.

Guess which one of the following can be used to shorten this code?

 var array = [12, 5, 42, 55, 10];
function func (arr) {
   for(let i=0; i<array.length; i++) {
       if(arr[i] > 30) {
          return arr[i];
       }
    }
}
// A
arr.find(i => i > 30);
// B
arr.findIndex(i => i > 30);
//C
arr.search(i => i > 30);

ABCNone9.

In the function below, what do we use Object.assign for?

 function func (param =
{}){
   var defaults = {
     color: 'red',
     shape: "square"
   };
   var s = Object.assign({}, defaults, param);
// ...
// Rest of function
}

We use it to provide default parameters to the function, which can be overridden.Create a string that contains ‘defaults’ and ‘param’.Checks if ‘defaults’ is equal to ‘param’.None10.

What is stored in the arr3 array?

var arr1 = [1,3],
var arr2 = [arr1, [5,5]],
var arr3 = [... arr2,[1,8]];

[ [1,3], [5,5], [1,8] ][1,3,5,5,1,8]23[5, 5, 1, 8]

Leave a Comment