Author: Alex

Translator: Front-end small wisdom

Source: dev. To

The more you know, the more you don’t know

Like and watch. Make it a habit


GitHub: github.com/qq449245884… Has been included, more past the classification of the highly praised articles, also collated a lot of my documentation, and tutorial materials. Welcome to Star and perfect, you can refer to the interview test point review, I hope we have something together.

ECMAScript 6 (ES6) is the next generation standard for the JS language. It was officially released in June 2015. Its goal is to make JS language can be used to write complex large applications, as an enterprise development language. Next let’s take a look at 20 tough interview questions, by doing the questions, while improving our JS skills.

Question1: Can explainES5ES6Is there a difference?

Subject: JavaScript Difficulty: ⭐⭐⭐

ECMAScript 5 (ES5) : The fifth edition of ECMAScript, standardized in 2009, is now fully supported in all modern browsers.

ECMAScript 6 (ES6)/ ECMAScript 2015 (ES2015): ECMAScript 6th Edition, standardized in 2015. This standard is already partially implemented in most modern browsers.

Here are some key differences between ES5 and ES6:

Arrow functions and string interpolation

const greetings = (name) => {
  return `hello ${name}`;
}
    
Copy the code

It can also be written like this:

const greetings = name => `hello ${name}`;    
Copy the code

Const: Const indicates that the original value of the variable cannot be modified. Note that const represents a constant reference to a value. We can change the property value of the object being referenced, but we cannot change the reference itself.

const NAMES = [];
NAMES.push("Jim");
console.log(NAMES.length === 1); // true
NAMES = ["Steve", "John"]; // error    
Copy the code

Block scope: in ES6, let, const creates a block-level scope and is not promoted like var declarations.

Default arguments: Default arguments allow us to initialize the function with default values. Default parameter values are used when parameters are omitted or undefined.

function multiply (a, b = 2) { return a * b; } multiply(5); / / 10Copy the code

Class definition and inheritance

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

The for – operator

for… The of statement creates a loop that traverses the iterable.

Expansion operator

const obj1 = { a: 1, b: 2 } const obj2 = { a: 2, c: 3, d: 4} const obj3 = {... obj1, ... obj2}Copy the code

Promises: Promises provide a mechanism to handle the results and errors of asynchronous operations. You can do the same thing with callbacks, but Promises improve readability with method linking and neat 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')
 })    
Copy the code

Module export

const myModule = { x: 1, y: () => { console.log('This is ES5') }}
export default myModule;   
Copy the code

And import

import myModule from './myModule';
Copy the code

Question 2: What is IIFE (immediately called function expression)

Subject: JavaScript Difficulty: ⭐⭐⭐

IIFE is an instant-call function expression that executes immediately after it is created

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

This pattern is often used to avoid fouling the global namespace, because all variables used in the IIFE (like any other ordinary function) are not visible outside of their scope.

Question 3: When to use arrow functions in ES6?

Subject: JavaScript Difficulty: ⭐⭐⭐

Here are some lessons to share:

  • Use function in the global scope and in the object.prototype property.

  • Use class for object constructors.

  • In other cases, use the arrow function.

Why are arrow functions used in most cases?

  • Scope security: When the arrow function is used consistently, everything is guaranteed to use the same thisObject as the root object. If a standard function callback is mixed up with a bunch of arrow functions, the scope can get messy.

  • Compactness: Arrow functions are easier to read and write.

  • Clarity: Use the arrow function to make it clear what this is currently pointing to.

Question 4: What is the purpose of introducing Symbol into ES6?

Subject: JavaScript Difficulty: ⭐⭐⭐

A Symbol is a new, special object that can be used as a unique attribute name in an object. Substituting Symbol for string avoids conflicting module attributes. You can also make symbols private so that no one who does not already have direct access to the Symbol can access their properties.

Symbol is the new basic JS data type. Like the number, String, and Boolean primitive types, Symbol has a function to create them. Unlike other primitive types, Symbol has no literal syntax. The only way to create them is to use the Symbol constructor in the following method

let symbol = Symbol();    
Copy the code

Question 5: What are the benefits of using spread syntax in ES6? How is it different from rest syntax?

Subject: JavaScript Difficulty: ⭐⭐⭐

ES6’s expansion syntax is useful when coding in functional form, because you can easily create copies of arrays or objects without resorting to object.create, slice, or library functions. This 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 };Copy the code

ES6’s REST syntax provides a shortcut to include any number of arguments to pass to a function.

Like the reverse of the expansion syntax, it puts and populates data into arrays rather than expanding them, and it is often used in function variables and array and object destructors.

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 }Copy the code

Question 6: What is the difference between an ES6 class and an ES5 function constructor?

Subject: JavaScript Difficulty: ⭐⭐⭐

// ES5 Function Constructor function Person(name) { this.name = name; } // ES6 Class class Person { constructor(name) { this.name = name; }}Copy the code

For simple constructors, they look very similar.

The main difference between constructors is the use of inheritance. If we create a Student subclass that inherits from Person and adds a studentId field, there are two ways to use it:

// ES5 Function Constructor Function Student(name, studentID) {// call your class Constructor to initialize members derived from your class. Person.call(this.name) // Initializes the members of the subclass. 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 } }Copy the code

Using inheritance in ES5 is much more complex, and the ES6 version is much easier to understand and remember.

Question 7:.call.applyWhat’s the difference?

Subject: JavaScript Difficulty: ⭐⭐⭐

Both.call and.apply are used to call the function, and the first argument is used as the value of this in the function. However,.call takes a comma-separated argument as the next argument, and.apply takes an array of arguments as the next argument. Simple memorization: C for call and comma separation, A for apply and parameter arrays.

function add(a, b) { return a + b; } console.log(add.call(null, 1, 2)); // 3 console.log(add.apply(null, [1, 2])); / / 3Copy the code

Question 8: Why use the ES6 class?

Subject: JavaScript Difficulty: ⭐⭐⭐

Some reasons for choosing to use classes:

  • The syntax is simpler and less error-prone.

  • It is easier (and less error-prone) to set up an inheritance hierarchy with the new syntax than with the old syntax.

  • Class avoids the common error of using new in constructors (making the constructor throw an exception if it is not a valid object).

  • Calling the version of the parent stereotype method with the new syntax is much simpler than the old syntax, With super method () instead of ParentConstructor. Prototype. Method. The call (this) Or Object. GetPrototypeOf (Object. GetPrototypeOf (this)). The call (this) method.

Consider the following code:

Using ES6 to achieve the above functions:

Question 9: What is the preferred syntax for defining enumerations in JS

Subject: JavaScript Difficulty: ⭐⭐⭐

Enumerations can be implemented by object.freeze

var DaysEnum = Object.freeze({
    "monday": 1,
    "tuesday": 2,
    "wednesday": 3,
    ...
})
Copy the code

or

var DaysEnum = {
    "monday": 1,
    "tuesday": 2,
    "wednesday": 3,
    ...
}
Object.freeze(DaysEnum)
Copy the code

However, this prevents us from assigning values to variables:

Let day = daysenum. Tuesday day = 298832342Copy the code

Question10: ExplainObject.freeze()constThe difference between

Subject: JavaScript Difficulty: ⭐⭐⭐

Const and object. freeze are two completely different concepts.

Const declares a read-only variable. Once declared, the value of the constant cannot be changed:

const person = {
    name: "Leonardo"
};
let animal = {
    species: "snake"
};
person = animal; // ERROR "person" is read-only    
    
Copy the code

Object.freeze applies to values, and more specifically to Object values, and makes the Object immutable, that is, its properties cannot be changed.

let person = {
    name: "Leonardo"
};
let animal = {
    species: "snake"
};
Object.freeze(person);
person.name = "Lima"; //TypeError: Cannot assign to read only property 'name' of object
console.log(person); 
    
Copy the code

Question 11: What is the promotion of JS

Subject: JavaScript Difficulty: ⭐⭐⭐⭐

Promotion is an operation by the JS interpreter to move all variable and function declarations to the top of the current scope. There are two types of promotion

  • Variable ascension
  • Function increase

As long as a var(or function declaration) is present in a scope, the declaration is considered to belong to the entire scope and can be accessed anywhere.

Function foo() {a = 3 console.log(a) // 3 var a} console.log(a) // 2Copy the code

Question 12: Explain the Prototype Pattern

Subject: JavaScript Difficulty: ⭐⭐⭐⭐

Instead of creating uninitialized objects, the stereotype pattern creates new objects, and it returns objects initialized with values copied from the stereotype or sample object. The stereotype pattern is also called the attribute pattern.

An example of a useful prototype pattern is to initialize a business object with a value that matches the default value in the database. The prototype object retains its default values, which will be copied to the newly created business object.

Traditional languages rarely use the prototype pattern, but JavaScript, as a prototype language, uses this pattern when building new objects and their prototypes.

Question 13. What are temporary dead zones in ES6

Subject: JavaScript Difficulty: ⭐⭐⭐⭐

In ES6, lets and const are promoted in the same way as var, class, and function, except that there is a period of time between entering the scope and being declared that they cannot be accessed. This period is called a temporary dead zone (TDZ).

//console.log(aLet) // would throw ReferenceError let aLet; console.log(aLet); // undefined aLet = 10; console.log(aLet); / / 10Copy the code

Question 14: When are arrow functions not used? Name three or more examples

Subject: JavaScript Difficulty: ⭐⭐⭐⭐

Here are some cases where you should not use arrow functions:

  • When you want the function to be promoted (the arrow function is anonymous)

  • To use this/arguments in a function, since the arrow functions themselves do not have this/arguments, they depend on the external context

  • Using named functions (arrow functions are anonymous)

  • When using a function as a constructor (arrow functions have no constructors)

  • When we want to add a function as a property to an object literal and use an object in it, we don’t have access to this, which is the object itself.

Question 15: What is the actual use of WeakMa P in ES6?

Subject: JavaScript Difficulty: ⭐⭐⭐⭐

WeakMaps provides a way to extend objects from the outside without affecting garbage collection. WeakMap can be applied when we want to extend an object but cannot because it is closed or from an external source.

WeakMap applies only to ES6 or later versions. WeakMap is a collection of key and value pairs, where keys must be objects.

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
Copy the code

The interesting thing about WeakMaps is that it contains weak references to the map’s internal keys. A weak reference means that if the object is destroyed, the garbage collector will delete the entire entry from the WeakMap, freeing up memory.

Question 16. Explain why the following methods cannot be used as IIFE. What changes would be needed to make them IIFE?

Subject: JavaScript Difficulty: ⭐⭐⭐⭐

function foo(){ }();
Copy the code

IIFE stands for immediately called function expression. The JS parser reads the function foo(){}(); As functions foo(){} and (); , the former is a function declaration, and the latter (a pair of parentheses) is an attempt to call a function without specifying a name, so it throws an Uncaught SyntaxError: Unexpected Token exception.

We can use the void function foo(){}(); . Unfortunately, there is a problem with this approach. The evaluation of a given expression is always undefined, so the IIFE function cannot be used if it returns a value, as shown below:

Const foo = void function bar() {console.log(' foo') return 'foo'; } (); console.log(foo); // undefinedCopy the code

Question 17: Can you compare the use of the module pattern with that of the constructor/prototype pattern?

Subject: JavaScript Difficulty: ⭐⭐⭐⭐

The module pattern is commonly used for namespaces, where a single instance is used as a store to group related functions and objects. This is a use case is different from the prototype design, they are not mutually exclusive, we can use them at the same time (for example, put a constructor in a module, and use the new MyNamespace. MyModule. MyClass (the arguments).

Constructors and prototypes are one of the logical ways to implement classes and instances. They don’t exactly correspond to the model, so you often need to choose a particular Scheme or helper method to implement the class in the prototype.

Question 18: What is the difference between ES6 Map and WeakMap?

Subject: JavaScript Difficulty: ⭐⭐⭐⭐⭐

They all behave differently when the object referenced by their key/value is deleted, as shown in the following 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); }) ()Copy the code

{x: 12} and {y: 12} are no longer referenced. The garbage collector continues to run and deletes the key B pointer from the WeakMa, as well as {y: 12} from memory.

But in the case of a Map, the garbage collector does not remove the pointer from the Map, nor does it remove {x: 12} from memory.

WeakMap allows the garbage collector to perform its collection task, but Map does not. For a manually written Map, the array retains a reference to the key object to prevent garbage collection. But in a WeakMap, references to key objects are retained “weakly,” which means that they do not prevent garbage collection in the absence of other object references.

Question 19. Give an example of a Curryization function and explain the benefits of curryization?

Subject: JavaScript Difficulty: ⭐⭐⭐⭐⭐

Curlization is a pattern in which a function with multiple arguments is decomposed into multiple functions that, when called in series, add up all the required arguments one at a time. This technique helps make code written functionally easier to read and write. Note that to implement a function, it needs to start with a function and then decompose into a series of functions, each of which takes one argument.

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]Copy the code

Question 20: How do I “deep freeze” objects in JS

Subject: JavaScript Difficulty: ⭐⭐⭐⭐⭐

If we want to ensure that the object is deeply frozen, we must create a recursive function to freeze each property of the object type:

No deep freeze

let person = {
    name: "Leonardo",
    profession: {
        name: "developer"
    }
};
Object.freeze(person); 
person.profession.name = "doctor";
console.log(person); //output { name: 'Leonardo', profession: { name: 'doctor' } }
Copy the code

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
Copy the code

The possible bugs after the deployment of code can not be known in real time, in order to solve these bugs, spent a lot of time log debugging, here by the way to recommend you a good BUG monitoring toolFundebug.

Original text: dev. To/fullstackca…

communication

The article is updated every week. You can search “Big Move World” on wechat for the first time to read and hurry up (one or two articles earlier than the blog yo). This article is GitHub github.com/qq449245884… Welcome to Star and improve. You can refer to the exam site for review during the interview. In addition, you can follow the public account and reply welfare in the background, so that you can see the welfare, you know.