26 selected JavaScript interview questions

Q1: What is the type conversion in JavaScript?

Topic: JavaScript 
Difficulty: 0

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

The following is an example of a display conversion:

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

 

The following 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!

 

Source:  FullStack.Cafe

Q2: What is the scope in JavaScript?

Topic: JavaScript 
Difficulty: ⭐

In JavaScript, each function has its own scope ( scope). A scope can be understood as a collection of variables and the corresponding rules for how to access it. Only variables inside the function can access variables in the function domain.

Within the same scope, the variable name must be unique. Scopes can be nested. In the innermost scope, you can access variables in any external scope.

Q3: Please explain the equality judgment in JavaScript

Topic: JavaScript 
Difficulty: ⭐

The equality judgment in JavaScript has two kinds of judgments: strict judgment and judgment with implicit conversion:

  • Strict judgment (strict comparision): For example ===, the comparison does not implicitly convert the type;
  • Abstract comparasion: For example ==, the type of implicit conversion is implicit.
var a = "42";
var b = 42;

a == b;         // true
a === b;        // false

Some simple rules:

  • If both sides are Boolean values, use ===;
  • If both sides are 0, ""[], use ===;
  • All other types ==are safe to use . And in many cases it simplifies the code and increases readability.

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

Topic: JavaScript 
Difficulty: ⭐⭐

A callback function is a function that is passed as a parameter to another function, which is called when some operations are finished. The following is a simple example. When the array is modified, the callback function is called to print a line of logs.

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);
});

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

Topic: JavaScript 
Difficulty: ⭐⭐

use strictPlace it at the top of the file or the first line of the function to initiate a more rigorous check to avoid errors caused by mistakes. For example, the following code will throw an error:

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

 

Since x is not defined, if used use strict, x is not treated as a global variable. The following code fixes this bug:

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

 

Q6: Please explain Null and Undefined

Topic: JavaScript 
Difficulty: ⭐⭐

JavaScript and TypeScript There are two basic types nulland undefined. Their meanings are different:

  • If it has not been initialized yet, yes undefined;
  • If not, it can nullbe represented;

Q7: Please implement the following function

Topic: JavaScript 
Difficulty: ⭐⭐

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

addSixIs a function, which means that the return of the createBase function 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);

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 means that after the event bound on the innermost element is triggered, it will be triggered step by step from the inside to the outside according to the nested level. Therefore, clicking on a child node may trigger an event on the parent node.

One way to prevent bubbling from events is to use them event.stopPropagation()on IE<9 browsers event.cancelBubble().

Source: 

Q10. Please explain the let keyword in JavaScript

Topic: JavaScript 
Difficulty: ⭐⭐

ES6 allows you to use the let keyword to declare {...}variables in the block scope ( ).

Source:  github.com/getify

Q11: How to check if a number is an integer?

Topic: JavaScript 
Difficulty: ⭐⭐

One of the easiest ways to determine if the remainder divided 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

Source:  coderbyte.com

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

Topic: JavaScript 
Difficulty: ⭐⭐

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

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

This method is used in common language to avoid polluting the global namespace, because the variables used in the IIFE are not accessible externally.

Source:  stackoverflow.com

Q13: If I compare two objects in JavaScript?

Topic: JavaScript 
Difficulty: ⭐⭐

Two non-basic types of values, such as objects (including functions and arrays), are accessed by reference. If you judge directly by ==and ===, you will simply judge whether their reference addresses are the same, not their actual corresponding values.

If the array is compared to a string, the array is converted to a string by comma stitching. When judging by the equal sign, two identical arrays are not equal, but are equal to the same data string.

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

a == c;     // true
b == c;     // true
a == b;     // false

If you want a deep comparison, you can use a third-party library, for example, deep-equalor you can implement a comparison algorithm yourself.

Q14: Please explain the difference between ES5 and ES6.

Topic: JavaScript 
Difficulty: ⭐⭐⭐

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

Next, introduce the main differences:

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

even:

const greetings = name => `hello ${name}`;

 

  • Constant declaration (Const): Like constants in other programming languages, but different. The constrepresentative here constant reference. That is, you can modify the value of the object it points to. But you can’t modify the value of its reference.
const NAMES = [];
NAMES.push("Jim");
console.log(NAMES.length === 1); // true
NAMES = ["Steve", "John"]; // error
  • Block Scope Variables: New keywords in ES6 letallow developers to limit the scope of variables to the block level. Will not varimprove like the same variable.
  • Parameter default: Allows you to specify a default value when the function is defined.
// Basic syntax
function multiply (a, b = 2) {
     return a * b;
}
multiply(5); // 10
  • Class definition and inheritance

ES6 began to support defining classes (using classkeywords), constructors (using constructorkeywords), and extendkeywords to implement inheritance.

  • For-of operation

for...ofStatements are used to iterate through all the properties 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}
  • Promise: Promises provides a way to handle asynchronous operations. You can do this with a callback function, but Promise is 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')
 })
  • Module export and import.
const myModule = { x: 1, y: () => { console.log('This is ES5') }}
export default myModule;

import myModule from './myModule';

Source:  Bulby.io

Q15: Please explain undefinedand not defineddifferences

Topic: JavaScript 
Difficulty: ⭐⭐⭐

In JavaScript, if you try to use a variable that doesn’t exist yet, JavaScript will throw an error var name is not defined. But if you use typeofto view its type, will return undefined.

Let’s first clarify the difference between a statement and a definition: it var xis a statement, because you have not defined its specific value, you just declare its existence.

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

 

var x = 1At the same time with both declarations and definitions, we can also call it initialization. In JavaScript, every variable and function declaration is promoted to the top.

If we access a declared but undefined variable, it will return undefined.

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

Accessing a variable that is not declared undefined will return a not defined error.

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

Source:  stackoverflow.com

Q16: What is the difference between anonymous functions 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();

Translator added: An anonymous function cannot be called if it is not assigned to a variable; it is not a superfluous name to be assigned again.

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

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

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

  • Scope of itself
  • 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

innerFunctionIs a closure, defined in outerFunctionit, which can access outerFunctionall variables of the scope. Of course, it also has access to global variables.

The output is as follows:

outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc

 

Source:  github.com/ganqqwerty

Q18: How do I create private variables in JavaScript?

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

You can create a private variable by declaring a variable in a function. Because in the function, the outside cannot be accessed directly.

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

console.log(priv); // throws error

To access this variable, you can construct a helper function to return the value.

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

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

Source: coderbyte.com

Q19: Please explain Prototype Design Pattern

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

Prototype mode creates a new object, but instead of creating an uninitialized object, it initializes by copying the value on the prototype chain or by copying the value of the object. Prototype patterns are rarely used in traditional languages, but JavaScript is a prototype-based language that uses prototype patterns to create new objects.

Source:  dofactory.com

Q20: Determine if the given string is homomorphic (isomorphic)

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

First introduce what is called homomorphism: two strings, if each character in the A string can find a unique correspondence in the B string, and the order one-to-one correspondence; if there is such a function, then A and B are homomorphic .

  • paperAnd titlehomomorphism
  • eggAnd saddifferent states
  • dggAnd addhomomorphism
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;
}

Source:  https://github.com/kennymkchan

Translator’s Note: The above solution is not correct. We made a slight change and gave the following correct answer:

/**
 * @param {string} firstString
 * @param {string} secondString
 * @return {boolean}
 */
var isIsomorphic = function(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) {
        // If letterB has already been added to letterMap, then not isomorphic
        if(secondString.indexOf(letterB) < i){
            return false;
           } else {
            letterMap[letterA] = letterB;            
        }
    } else if (letterMap[letterA] !== letterB) {
      // Else 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;
};

Q21:  TranspilingWhat does it mean?

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

TranspilingYes transforming + compiling, the compound word. For some new syntax, the browser does not support it. The best way is to transform it to the old equivalent code, which is usually called transpiling.

Typically, you can buildjoin in the process transpiler, just like the code lintersum minifier.

There are already many well-known transpilers available:

  • Babel: Compiling ES6 to ES5
  • Traceur: Compile ES6, ES7, etc. to ES5

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

Q22:  thisHow does the keyword work? Please provide some examples

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

In JavaScript, this always points 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

Source:  quirksmode.org

Q23: How to add your own custom function to the Array object so that the following code works fine.

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

var arr = [1, 2, 3, 4, 5];
var avg = arr.average();
console.log(avg);

JavaScript is a prototype-based language. This means that objects are linked by prototypes and inherit their functions. To add a function 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

Source:  coderbyte.com

Q24: What does hoisting mean in JavaScript?

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

Hoisting means that the JavaScript interpreter promotes all variables and function declarations to the top of the scope. There are two types of promotion:

  • Variable promotion
  • Function boost

Variables and functions declared in a 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

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

Q25: What results will be returned by the following code?

Topic: JavaScript 
Difficulty: ⭐⭐⭐⭐

0.1 + 0.2 === 0.3

Don’t be surprised, 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 results.

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, but to expose variables and functions that need to be exposed. A straightforward implementation is as follows:

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

You May Also Like

About the Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *