Translator: Here are 26 questions selected from different platforms to help you interview

  • 原文: Top 26 JavaScript Interview Questions I Wish I Knew
  • Translator: Fundebug

In order to ensure readability, this paper adopts free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, translation is only for learning.

According to Stack Overflow’s 2018 annual survey, JavaScript has held the record for the most used programming language for six consecutive years. For a full-stack engineer, JavaScript is a must-have language and is always asked about in interviews. I’ve compiled a list of all the common JavaScript interview questions at Fullstack. Cafe for your reference:

Q1: What does cast look like in JavaScript?

Topic: JavaScript difficulty: 0

In JavaScript, a conversion between two different types is called an coercion. In JavaScript there are two forms: a display transformation and an implicit transformation.

Here is an example showing the transformation:

var a = "42";
var b = Number( a );
a;              42 "/ /"
b;              // 42 -- the number!
Copy the code

Here is an example of an implicit conversion:

var a = "42";
var b = a * 1;  // "42" implicitly coerced to 42 here
a;              42 "/ /"
b;              // 42 -- the number!
Copy the code

Source: FullStack. Cafe

Q2: What does scope look like in JavaScript?

Topic: JavaScript difficulty: ⭐

In JavaScript, each function has its own scope. A scope can be thought of as a collection of variables and corresponding rules about how to access them. Only variables inside a function can access variables in that function domain.

Variable names must be unique within the same scope. Scopes can be nested. In the innermost scope, variables in any outer scope can be accessed.

Q3: Please explain the equality judgment in JavaScript

Topic: JavaScript difficulty: ⭐

There are two kinds of equality judgment in JavaScript: strict judgment and implicit conversion judgment:

  • Strict Comparision: For example= = =, the comparison does not implicitly convert the type;
  • Abstractasion: For example, you can talk about it= =, the comparison will implicitly convert the type.
var a = "42";
var b = 42;

a == b;         // true
a === b;        // false
Copy the code

Some simple rules:

  • If both sides are Boolean values, use= = =;
  • If we have 0 on both sides,"".[], the use of= = =;
  • For all other types, use= =It’s safe. And in many cases it simplifies the code and increases readability.

Q4: Explain what a callback function is and provide a simple example

Topic: JavaScript difficulty: ⭐⭐

A callback function is a function that is passed as an argument to another function and is called when some operation has finished. Here is a simple example of calling a callback function to print a log line when the array has been modified.

function modifyArray(arr, callback) {
  // do something to arr here
  arr.push(100);
  // then execute the callback function that was passed
  callback();
}

var arr = [1.2.3.4.5];
modifyArray(arr, function() {
  console.log("array has been modified", arr);
});
Copy the code

Q5: What is the use of “use strict”?

Topic: JavaScript difficulty: ⭐⭐

Use strict is placed at the top of the file or the first line of a function to enable more stringent checks to avoid errors caused by errors. For example, the following code throws an error:

function doSomething(val) {
  "use strict"; 
  x = val + 10;
}
Copy the code

Since x is undefined, if use is strict, x will not be treated as a global variable. The following code fixes this BUG:

function doSomething(val) {
  "use strict"; 
  var x = val + 10;
}
Copy the code

Q6: Please explain Null and Undefined

Topic: JavaScript difficulty: ⭐⭐

JavaScript and TypeScript have two basic types: null and undefined. Their meanings are different:

  • Yes if it has not been initializedundefined;
  • If it is not available, it is availablenullTo represent;

Q7: Please implement the following functions

Topic: JavaScript difficulty: ⭐⭐

var addSix = createBase(6);
addSix(10); // returns 16
addSix(21); // returns 27
Copy the code

AddSix is a function, that is, the return of createBase is a function.

function createBase(baseNumber) {
  return function(N) {
    // we are referencing baseNumber here even though it was declared
    // outside of this function. Closures allow us to do this in JavaScript
    returnbaseNumber + N; }}var addSix = createBase(6);
addSix(10);
addSix(21);
Copy the code

Q8: Please interpret the values and types in JavaScript

Topic: JavaScript difficulty: ⭐⭐

Here are the available types built into JavaScript:

  • string
  • number
  • boolean
  • Null, and undefined
  • object
  • Symbol (new syntax for ES6)

Q9: Explain the event bubble and how to stop it?

Topic: JavaScript difficulty: ⭐⭐

The concept of event bubbling is that events bound to the innermost element are triggered from the inside out, according to the level of nesting. Therefore, clicking on a child node may trigger an event on the parent node.

One way to stop events from bubbling is to use event.stopPropagation() and event.cancelbubble in IE<9.

function stopPropagation(evt) {
    if (typeof evt.stopPropagation === "function") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true; }}Copy the code

Source: github.com/kennymkchan

Q10. Please explain the let keyword in JavaScript

Topic: JavaScript difficulty: ⭐⭐

ES6 allows you to declare block scope using the let keyword ({… }).

Source: github.com/getify

Q11: How do I check if a number is an integer?

Topic: JavaScript difficulty: ⭐⭐

One of the easiest ways to do this is to determine whether the remainder of dividing by 1 is 0.

function isInt(num) {
  return num % 1= = =0;
}

console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false
Copy the code

Source: coderbyte.com

Q12: What is IIFEs(Immediately Invoked Function Expressions)?

Topic: JavaScript difficulty: ⭐⭐

IIFE is called an immediate execution expression, and as the name implies, the expression is executed as soon as it is created.

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

This method usage avoids fouling the global namespace because variables used in the IIFE are not externally accessible.

Source: stackoverflow.com

Q13: What if you compare two objects in JavaScript?

Topic: JavaScript difficulty: ⭐⭐

Values of two non-basic types, such as objects (including functions and arrays), are accessed by reference. If you use == and === directly, you will simply determine whether they are referenced to the same address, not their actual value.

If an array is compared to a string, the array is converted to a string by comma concatenation. Two identical arrays are not equal, but compared to a string with the same data.

var a = [1.2.3];
var b = [1.2.3];
var c = "1, 2, 3";

a == c;     // true
b == c;     // true
a == b;     // false
Copy the code

For deep comparisons, use a third-party library such as deep-Equal or implement a comparison algorithm yourself.

Q14: Explain the differences between ES5 and ES6

Topic: JavaScript difficulty: ⭐⭐⭐

  • ECMAScript 5 (ES5): The fifth version of ECMAScript, standardized in 2009. The standard is fully supported by almost all browsers.
  • ECMAScript 6 (ES6)/ECMAScript 2015 (ES2015): The sixth version of ECMAScript, standardized in 2015. It is currently only partially supported by major browsers.

Here are the main differences:

  • Arrow functions and strings are embedded:
const greetings = (name) = > {
      return `hello ${name}`;
}
Copy the code

Even:

const greetings = name= > `hello ${name}`;
Copy the code
  • Constant declaration (Const): Like constants in other programming languages, but with a difference. Here,constOn behalf of theconstant reference. That is, you can change the value of the object to which it points. However, you cannot change the value of the reference.
const NAMES = [];
NAMES.push("Jim");
console.log(NAMES.length === 1); // true
NAMES = ["Steve"."John"]; // error
Copy the code
  • Block-scoped variables: new keywords in ES6letAllow Allows developers to scope variables at the block level. Don’t likevarThe same variable goes up.
  • Parameter defaults: Allows default values to be specified during function definition.
// Basic syntax
function multiply (a, b = 2) {
     return a * b;
}
multiply(5); / / 10
Copy the code
  • Class definition and inheritance

ES6 began to support defining classes (using the class keyword), constructors (using the constructor keyword), and the extend keyword to implement inheritance.

  • The for – operation

for… The of statement is used to iterate through all the properties of an object.

  • Spread operator: for object merging
const obj1 = { a: 1.b: 2 }
const obj2 = { a: 2.c: 3.d: 4}
constobj3 = {... obj1, ... obj2}Copy the code
  • Promises: Promises provide a way to handle asynchronous operations. You can do this with callbacks, but promises are much more concise and readable.
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
  • The export and import of the module.
const myModule = { x: 1.y: (a)= > { console.log('This is ES5')}}export default myModule;
Copy the code
import myModule from './myModule';
Copy the code

Source: Bulby. IO

Q15: please explainundefinedandnot definedThe difference between

Topic: JavaScript difficulty: ⭐⭐⭐

In JavaScript, if you try to use an undeclared variable that does not exist, JavaScript throws the error var name is not defined. But if you use typeof to see what type it is, undefined is returned.

Let’s clarify the difference between a declaration and a definition: var x is a declaration because you’re not defining its value, you’re just declaring its existence.

var x; // declaring x
console.log(x); //output: undefined
Copy the code

Var x = 1 is both declared and defined, or we can call it initialized. In JavaScript, every variable and function declaration is promoted to the top.

If we access a declared but undefined variable, undefined is returned.

var x; // Declaration
if(typeof x === 'undefined') // Will return true
Copy the code

Accessing an undeclared undefined variable returns a not defined error.

console.log(y);  // Output: ReferenceError: y is not defined
Copy the code

Source: stackoverflow.com

Q16: What’s the difference between anonymous and named functions?

Topic: JavaScript difficulty: ⭐⭐⭐

var foo = function() { // anonymous function assigned to variable foo
    // ..
};

var x = function bar(){ // named function (bar) assigned to variable x 
    // ..
};

foo(); // actual function execution
x();
Copy the code

Anonymous functions cannot be called if they are not assigned to a variable. The named function gets assigned again.

Q17: What is a closure in JavaScript? Please provide an example

Topic: JavaScript difficulty: ⭐⭐⭐⭐

A closure is a function that is defined inside another function (parent function) and has access to variables in the parent function. Closures have access to the following three scopes:

  • Its own scope
  • The parent scope
  • Global scope
var globalVar = "abc";

// Parent self invoking function
(function outerFunction (outerArg) { // begin of scope outerFunction
  // Variable declared in outerFunction function scope
  var outerFuncVar = 'x';    
  // Closure self-invoking function
  (function innerFunction (innerArg) { // begin of scope innerFunction
    // variable declared in innerFunction function scope
    var innerFuncVar = "y";
    console.log(         
      "outerArg = " + outerArg + "\n" +
      "outerFuncVar = " + outerFuncVar + "\n" +
      "innerArg = " + innerArg + "\n" +
      "innerFuncVar = " + innerFuncVar + "\n" +
      "globalVar = " + globalVar);
  // end of scope innerFunction}) (5); // Pass 5 as parameter
// end of scope outerFunction}) (7); // Pass 7 as parameter
Copy the code

InnerFunction is a closure defined in outerFunction, which has access to all variables in the outerFunction scope. Of course, it can also access global variables.

The output is as follows:

outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc
Copy the code

Source: github.com/ganqqwerty

Q18: How do YOU create private variables in JavaScript?

Topic: JavaScript difficulty: ⭐⭐⭐⭐

You can create private variables by declaring them in a function. Because in the function, the external is not directly accessible.

function func() {
  var priv = "secret code";
}

console.log(priv); // throws error
Copy the code

To access the variable, a helper function can be constructed to return the value.

function func() {
  var priv = "secret code";
  return function() {
    returnpriv; }}var getPriv = func();
console.log(getPriv()); // => secret code
Copy the code

Source: coderbyte.com

Q19: Please explain the Prototype Design Pattern

Topic: JavaScript difficulty: ⭐⭐⭐⭐

The stereotype pattern creates a new object, but instead of creating an uninitialized object, the initialization is done by copying the values on the stereotype chain or the values of the copied objects. Traditional languages rarely use the stereotype pattern, but JavaScript, as a prototype-based language, uses the stereotype pattern to create new objects.

Source: dofactory.com

Q20: Determine whether a given string is isomorphic

Topic: JavaScript difficulty: ⭐⭐⭐⭐

First, what is called homomorphism: two strings, if each character in string A can be uniquely matched in string B, and the order is one-to-one; If such A function exists, then A and B are homomorphic.

  • paperandtitlehomomorphic
  • eggandsadDifferent states
  • dggandaddhomomorphic
isIsomorphic("egg".'add'); // true
isIsomorphic("paper".'title'); // true
isIsomorphic("kick".'side'); // false

function isIsomorphic(firstString, secondString) {

  // Check if the same length. If not, they cannot be isomorphic
  if(firstString.length ! == secondString.length)return false

  var letterMap = {};

  for (var i = 0; i < firstString.length; i++) {
    var letterA = firstString[i],
        letterB = secondString[i];

    // If the letter does not exist, create a map and map it to the value
    // of the second letter
    if (letterMap[letterA] === undefined) {
      letterMap[letterA] = letterB;
    } else if(letterMap[letterA] ! == letterB) {// Eles if letterA already exists in the map, but it does not map to
      // letterB, that means that A is mapping to more than one letter.
      return false; }}// If after iterating through and conditions are satisfied, return true.
  // They are isomorphic
  return true;
}
Copy the code

Source: github.com/kennymkchan

Q21: TranspilingWhat does it mean?

Topic: JavaScript difficulty: ⭐⭐⭐⭐

Transpiling is the compound word for transforming + compiling. Some of the new syntax is not yet supported by the browser. The best way to do this is to convert to the old equivalent code, a process often called transpiling.

Typically, you can add transpiler to the build process, just as you can with code Linter and Minifier.

There are already a number of well-known transpilers available:

  • Babel: Compile ES6 into ES5
  • Traceur: Compile ES6,ES7, etc to ES5

Source: You Don’t Know JS, Up &going

Q22: thisHow do keywords work? Please provide some examples

Topic: JavaScript difficulty: ⭐⭐⭐⭐

In JavaScript, this always refers to the “owner” of a function (that is, the object that points to the function), or the object that owns the function.

function foo() {
    console.log( this.bar );
}

var bar = "global";

var obj1 = {
    bar: "obj1".foo: foo
};

var obj2 = {
    bar: "obj2"
};

foo();          // "global"
obj1.foo();     // "obj1"
foo.call( obj2 );  // "obj2"
new foo();       // undefined
Copy the code

Source: quirksmode.org

Q23: How to add your own functions to Array objects to make the following code work.

Topic: JavaScript difficulty: ⭐⭐⭐⭐

var arr = [1.2.3.4.5];
var avg = arr.average();
console.log(avg);
Copy the code

JavaScript is a prototype-based language. That is, objects are linked to each other via archetypes and inherit their functions. To add functions to an Array object, we can modify its prototype definition Array ProroType.

Array.prototype.average = function() {
  // calculate sum
  var sum = this.reduce(function(prev, cur) { return prev + cur; });
  // return sum divided by number of elements
  return sum / this.length;
}

var arr = [1.2.3.4.5];
var avg = arr.average();
console.log(avg); / / = > 3
Copy the code

Source: coderbyte.com

In JavaScript, what does it mean to upgrade?

Topic: JavaScript difficulty: ⭐⭐⭐⭐

In the case of hoist, the JavaScript interpreter presses all variable and function declarations to the top of the scope. There are two types of hoist:

  • Variable ascension
  • Function increase

Variables and functions declared in one scope can be used throughout the scope.

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

Although the foo() function is defined later, it can also be called earlier.

Q25: What does the following code return?

Topic: JavaScript difficulty: ⭐⭐⭐⭐

0.1 + 0.2= = =0.3
Copy the code

Not surprisingly, the result is false. Because of the accuracy of floating point numbers in the system, the result of 0.1+0.2 is not 0.3, but 0.30000000000000004. The way to avoid this problem is to specify the number of decimal places to return the result.

Source: coderbyte.com

Q26: Please describe the Revealing Module Pattern.

Topic: JavaScript difficulty: ⭐⭐⭐⭐⭐

A variant of the Module pattern is Revealing Module pattern. The purpose of this design pattern is to achieve good code isolation, exposing only variables and functions that need to be exposed. A straightforward implementation would look like this:

var Exposer = (function() {
  var privateVariable = 10;

  var privateMethod = function() {
    console.log('Inside a private method! ');
    privateVariable++;
  }

  var methodToExpose = function() {
    console.log('This is a method I want to expose! ');
  }

  var otherMethodIWantToExpose = function() {
    privateMethod();
  }

  return {
      first: methodToExpose,
      second: otherMethodIWantToExpose }; }) (); Exposer.first();// Output: This is a method I want to expose!
Exposer.second();       // Output: Inside a private method!
Exposer.methodToExpose; // undefined
Copy the code

Source: pausing. IO

About Fundebug

Fundebug focuses on real-time BUG monitoring for JavaScript, wechat mini programs, wechat mini games, Alipay mini programs, React Native, Node.js and Java online applications. Since the official launch of Double Eleven in 2016, Fundebug has handled a total of 1 billion + error events. Paying customers include Google, 360, Kingsoft, Minming.com and many other brands. Welcome to try it for free!

Copyright statement

Reprint please indicate the author Fundebug and this article addresses: blog.fundebug.com/2018/10/18/…