We’ve compiled 26 simple and in-depth questions from various platforms to help you with your interview

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

For the sixth year in a row, JavaScript holds the record as the most commonly used programming language, according to Stack Overflow’s 2018 annual survey. For a full-stack engineer, JavaScript is a must-have language and is often asked in interviews. I’ve compiled all the common JavaScript interview questions from fullstack.cafe for your reference:

Q1: How do type conversions work in JavaScript?

Topic: JavaScript Difficulty: 0

In JavaScript, the conversion between two different types is called coercion. There are two forms in JavaScript: explicit conversions and implicit conversions.

Here is an example of a display 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

Q2: What does scope look like in JavaScript?

Topic: JavaScript Difficulty: ⭐

In JavaScript, each function has its own scope. A scope can be understood as a collection of variables and the corresponding rules for 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, you can access any variable in the outer scope.

Q3: 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: no implicit type conversion when comparing, for example ===; Abstract comparasion: when you compare things like ==, the type is implicitly converted.

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 both sides are 0,””,[], use ===;
  • For all other types, it is safe to use ==. And in many cases it simplifies code and increases readability.

Q4: Please explain what a callback is and provide a simple example

Topic: JavaScript Difficulty: ⭐⭐

A callback function is a function that is passed as an argument to another function that is called when some operation has finished. Here is a simple example of calling a callback function to print a line of log when the array is 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 the function to initiate stricter checks to avoid error-caused 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 strict is used, x is not 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. They have different meanings:

  • Undefined if it has not been initialized;
  • If not available, use null.

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, which means that the return from 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
    return baseNumber + N;
  }
}

var addSix = createBase(6);
addSix(10);
addSix(21);
Copy the code

Q8: Please explain 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: Please explain the event bubbling and how to stop it?

Topic: JavaScript Difficulty: ⭐⭐

The concept of event bubbling is that events bound to the innermost element are triggered and then emitted from inside out in a nested hierarchy. Therefore, clicking on a child node might trigger an event for the parent node.

One way to prevent event bubblers is to use event.stopPropagation(), using Event.cancelBubble () in IE<9.

Source: github.com/kennymkchan

Q10. Explain the let keyword in JavaScript

Topic: JavaScript Difficulty: ⭐⭐

ES6 allows you to declare block scopes 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 that is to determine whether the remainder of dividing by 1 is 0.

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

console.log(isInt(4)); // trueThe console. The log (isInt (12.2)); //falseThe console. The log (isInt (0.3)); //false
Copy the code

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

Topic: JavaScript Difficulty: ⭐⭐

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

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

This method is commonly used to avoid polluting the global namespace because all variables used in IIFE are not externally accessible.

Q13: How do 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 the reference addresses are the same, rather than their actual values.

If an array is compared to a string, the array is converted to a string by comma concatenation. Using the equality sign, two arrays of the same value are not equal, but are compared to strings of 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, you can use a third-party library such as deep-Equal or implement a comparison algorithm yourself.

Q14: Please explain the difference 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. Currently, it is only partially supported by major browsers.

Here are the main differences:

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

Even:

const greetings = name => `hello ${name}`;
Copy the code
  • Const declarations: Like constants in other programming languages, but different. Const here represents the constant reference. That is, you can change the value of the object it points to. But you cannot change the value of its reference.
const NAMES = [];
NAMES.push("Jim");
console.log(NAMES.length === 1); // true
NAMES = ["Steve"."John"]; // error
Copy the code
  • Block-scoped variables: The new keyword let in ES6 allows developers to limit the scope of variables to the block level. It doesn’t scale up like var does.
  • Parameter Defaults: Allows you to specify default values during function definition.
// Basic syntax
function multiply (a, b = 2) {
     returna * b; } multiply(5); / / 10Copy the code
  • Class Definition and inheritance ES6 starts to support defining classes (using the class keyword), constructors (using the constructor keyword), and extend keywords to implement inheritance.
  • The for – operation

for… The of statement is used to iteratively access all attributes of an object.

  • Spread operator: used for object merging
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 way to handle asynchronous operations. You can implement this with callback functions, but promises are much cleaner and more 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
  • Export and import of modules.
const myModule = { x: 1, y: () => { console.log('This is ES5')}}export default myModule;
Copy the code
import myModule from './myModule';
Copy the code

Q15: Please explain the difference between undefined and not defined

Topic: JavaScript Difficulty: ⭐⭐⭐

In JavaScript, if you try to use an undeclared variable that doesn’t exist, JavaScript throws an error var name is not defined. But if you use typeof to view its type, undefined is returned.

Let’s clarify the difference between a declaration and a definition: var x is a declaration because you don’t define its value, you just declare 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 initialization. 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 and undefined variable returns a not defined error.

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

Q16: What is 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. It’s unnecessary to assign a named function again.

Q17: What are closures in JavaScript? Please provide an example

⭐⭐⭐⭐

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

  • Scope of itself
  • 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 the outerFunction that accesses all variables in the outerFunction scope. Of course, it also has access to global variables.

The following output is displayed:

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

Q18: How do I create private variables in JavaScript?

⭐⭐⭐⭐

You can create private variables by declaring them in functions. Because in a function, the outside 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() {
    return priv;
  }
}

var getPriv = func();
console.log(getPriv()); // => secret code
Copy the code

Q19: Prototype Design Pattern

⭐⭐⭐⭐

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

Source: dofactory.com

Q20: Judge whether a given string is isomorphic

⭐⭐⭐⭐

First, what is called A homomorphism: two strings, if each character in the string A can be found in A unique correspondence in the string B, and the sequence corresponds one to one; If such A function exists, then A and B are homomorphic.

  • Paper and title are homomorphic
  • Egg and SAD have different states
  • DGG and add are homomorphic
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) { // Elesif 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

Q21: Transpiling stands for what?

⭐⭐⭐⭐

Transpiling is a amalgam of transforming + compiling. For some of the new syntax, browsers don’t support it yet. The best way to do this is to transform it to the old equivalent code, a process commonly known as transpiling.

Typically, you can include transpilers during builds, just like code linters and minifiers.

There are many well-known transpilers available:

  • Babel: Compile ES6 to ES5
  • Traceur: Compile ES6,ES7, and so on to ES5

You Don’t Know JS, Up &going

Q22: How does this keyword work? Please provide some examples

⭐⭐⭐⭐

In JavaScript, this always refers to the “owner” of the 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

Q23: How to add your own custom functions to an Array object to make the following code work.

⭐⭐⭐⭐

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 by stereotypes and inherit their functions. To add a function to an Array object, we can modify its prototype to define 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
  returnsum / this.length; } var arr = [1, 2, 3, 4, 5]; var avg = arr.average(); console.log(avg); / / = > 3Copy the code

Q24: what does ascending (as of July 1) mean in JavaScript?

⭐⭐⭐⭐

Promotion (as of 1997) means that the JavaScript interpreter lifts all variable and function declarations to the top of that scope. There are two types of promotion:

  • Variable ascension
  • Function increase

Variables and functions declared in one scope are available in the entire 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 ); / / 2Copy the code

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

Q25: What result does the following code return?

⭐⭐⭐⭐

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, 0.1+0.2 is not 0.3, but 0.30000000000000004. One 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.

⭐⭐⭐⭐⭐

A variation of the Module pattern is Revealing Module pattern. The purpose of this design pattern is to achieve good code isolation, only exposing variables and functions that need to be exposed. A direct 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 }; }) ();Copy the code

Copyright statement

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