Top 26 JavaScript Interview Questions I Wish I Knew

Alex 👨🏼‍💻FullStack.Cafe - Sep 24 '18 - - Dev Community

Top 26 JavaScript Interview Questions I Wish I Knew
According to Stack Overflow’s Annual Survey of 2018, JavaScript becomes the most commonly used programming language, for the six years in a row. Let's face it, JavaScript is a cornerstone of your Full Stack Developer skills and can't be avoided on any Developer's Interview. Follow through and read the FullStack.Cafe compilation of the most common and tricky JavaScript Interview Questions and Answers to land your next dream job.

🔴 Originally published on FullStack.Cafe - Kill Your Tech & Coding Interview

Q1: What is Coercion in JavaScript?

Topic: JavaScript
Difficulty:

In JavaScript conversion between different two build-in types called coercion. Coercion comes in two forms in JavaScript: explicit and implicit.

Here's an example of explicit coercion:

var a = "42";

var b = Number( a );

a;              // "42"
b;              // 42 -- the number!
Enter fullscreen mode Exit fullscreen mode

And here's an example of implicit coercion:

var a = "42";

var b = a * 1;  // "42" implicitly coerced to 42 here

a;              // "42"
b;              // 42 -- the number!
Enter fullscreen mode Exit fullscreen mode

🔗 Source: FullStack.Cafe

Q2: What is Scope in JavaScript?

Topic: JavaScript
Difficulty: ⭐

In JavaScript, each function gets its own scope. Scope is basically a collection of variables as well as the rules for how those variables are accessed by name. Only code inside that function can access that function's scoped variables.

A variable name has to be unique within the same scope. A scope can be nested inside another scope. If one scope is nested inside another, code inside the innermost scope can access variables from either scope.

🔗 Source: FullStack.Cafe

Q3: Explain equality in JavaScript

Topic: JavaScript
Difficulty: ⭐

JavaScript has both strict and type–converting comparisons:

  • Strict comparison (e.g., ===) checks for value equality without allowing coercion
  • Abstract comparison (e.g. ==) checks for value equality with coercion allowed
var a = "42";
var b = 42;

a == b;         // true
a === b;        // false
Enter fullscreen mode Exit fullscreen mode

Some simple equalityrules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

🔗 Source: FullStack.Cafe

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

Topic: JavaScript
Difficulty: ⭐⭐

A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console after some operations have been completed.

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);
});
Enter fullscreen mode Exit fullscreen mode

🔗 Source: coderbyte.com

Q5: What does "use strict" do?

Topic: JavaScript
Difficulty: ⭐⭐

The use strict literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake. For example, the following program will throw an error:

function doSomething(val) {
  "use strict"; 
  x = val + 10;
}`
Enter fullscreen mode Exit fullscreen mode

It will throw an error because x was not defined and it is being set to some value in the global scope, which isn't allowed with use strict The small change below fixes the error being thrown:

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

🔗 Source: coderbyte.com

Q6: Explain Null and Undefined in JavaScript

Topic: JavaScript
Difficulty: ⭐⭐

JavaScript (and by extension TypeScript) has two bottom types: null and undefined. They are intended to mean different things:

  • Something hasn't been initialized : undefined.
  • Something is currently unavailable: null.

🔗 Source: FullStack.Cafe

Q7: Write a function that would allow you to do this.

Topic: JavaScript
Difficulty: ⭐⭐

var addSix = createBase(6);
addSix(10); // returns 16
addSix(21); // returns 27
Enter fullscreen mode Exit fullscreen mode

You can create a closure to keep the value passed to the function createBase even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable baseNumber.

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);
Enter fullscreen mode Exit fullscreen mode

🔗 Source: coderbyte.com

Q8: Explain Values and Types in JavaScript

Topic: JavaScript
Difficulty: ⭐⭐

JavaScript has typed values, not typed variables. The following built-in types are available:

  • string
  • number
  • boolean
  • null and undefined
  • object
  • symbol (new to ES6)

🔗 Source: FullStack.Cafe

Q9: Explain event bubbling and how one may prevent it

Topic: JavaScript
Difficulty: ⭐⭐

Event bubbling is the concept in which an event triggers at the deepest possible element, and triggers on parent elements in nesting order. As a result, when clicking on a child element one may exhibit the handler of the parent activating.

One way to prevent event bubbling is using event.stopPropagation() or event.cancelBubble on IE < 9.

🔗 Source: https://github.com/kennymkchan

Q10: What is let keyword in JavaScript?

Topic: JavaScript
Difficulty: ⭐⭐

In addition to creating declarations for variables at the function level, ES6 lets you declare variables to belong to individual blocks (pairs of { .. }), using the let keyword.

🔗 Source: github.com/getify

Q11: How would you check if a number is an integer?

Topic: JavaScript
Difficulty: ⭐⭐

A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1.

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

console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false
Enter fullscreen mode Exit fullscreen mode

🔗 Source: coderbyte.com

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

Topic: JavaScript
Difficulty: ⭐⭐⭐

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created:

(function IIFE(){
    console.log( "Hello!" );
})();
// "Hello!"
Enter fullscreen mode Exit fullscreen mode

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

🔗 Source: stackoverflow.com

Q13: How to compare two objects in JavaScript?

Topic: JavaScript
Difficulty: ⭐⭐⭐

Two non-primitive values, like objects (including function and array) held by reference, so both == and === comparisons will simply check whether the references match, not anything about the underlying values.

For example, arrays are by default coerced to strings by simply joining all the values with commas (,) in between. So two arrays with the same contents would not be == equal:

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

a == c;     // true
b == c;     // true
a == b;     // false
Enter fullscreen mode Exit fullscreen mode

For deep object comparison use external libs like deep-equal or implement your own recursive equality algorithm.

🔗 Source: FullStack.Cafe

Q14: Could you explain the difference between ES5 and ES6

Topic: JavaScript
Difficulty: ⭐⭐⭐

  • 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:

  • Arrow functions & string interpolation: Consider:
const greetings = (name) => {
      return `hello ${name}`;
}
Enter fullscreen mode Exit fullscreen mode

and even:

const greetings = name => `hello ${name}`;
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • 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.
  • 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
Enter fullscreen mode Exit fullscreen mode
  • Class Definition and Inheritance

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

  • for-of operator

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

  • Spread Operator
    For objects merging

const obj1 = { a: 1, b: 2 }
const obj2 = { a: 2, c: 3, d: 4}
const obj3 = {...obj1, ...obj2}
Enter fullscreen mode Exit fullscreen mode
  • 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')
 })
Enter fullscreen mode Exit fullscreen mode
  • Modules exporting & importing Consider module exporting:
const myModule = { x: 1, y: () => { console.log('This is ES5') }}
export default myModule;
Enter fullscreen mode Exit fullscreen mode

and importing:

import myModule from './myModule';
Enter fullscreen mode Exit fullscreen mode

🔗 Source: Bulby.io

Q15: Explain the difference between "undefined" and "not defined" in JavaScript

Topic: JavaScript
Difficulty: ⭐⭐⭐

In JavaScript if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and the script will stop execute thereafter. But If you use typeof undeclared_variable then it will return undefined.

Before starting further discussion let's understand the difference between declaration and definition.

var x is a declaration because you are not defining what value it holds yet, but you are declaring its existence and the need of memory allocation.

var x; // declaring x
console.log(x); //output: undefined
Enter fullscreen mode Exit fullscreen mode

var x = 1 is both declaration and definition (also we can say we are doing initialisation), Here declaration and assignment of value happen inline for variable x, In JavaScript every variable declaration and function declaration brings to the top of its current scope in which it's declared then assignment happen in order this term is called hoisting.

A variable that is declared but not define and when we try to access it, It will result undefined.

var x; // Declaration
if(typeof x === 'undefined') // Will return true
Enter fullscreen mode Exit fullscreen mode

A variable that neither declared nor defined when we try to reference such variable then It result not defined.

console.log(y);  // Output: ReferenceError: y is not defined
Enter fullscreen mode Exit fullscreen mode

🔗 Source: stackoverflow.com

Q16: What is the difference between anonymous and named functions?

Topic: JavaScript
Difficulty: ⭐⭐⭐

Consider:

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();
Enter fullscreen mode Exit fullscreen mode

🔗 Source: FullStack.Cafe

Q17: What is “closure” in javascript? Provide an example?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope.

The closure has access to variable in three scopes:

  • Variable declared in his own scope
  • Variable declared in parent function scope
  • Variable declared in global namespace
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
Enter fullscreen mode Exit fullscreen mode

innerFunction is closure which is defined inside outerFunction and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in global namespace.

Output of above code would be:

outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc
Enter fullscreen mode Exit fullscreen mode

🔗 Source: github.com/ganqqwerty

Q18: How would you create a private variable in JavaScript?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

To create a private variable in JavaScript that cannot be changed you need to create it as a local variable within a function. Even if the function is executed the variable cannot be accessed outside of the function. For example:

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

console.log(priv); // throws error
Enter fullscreen mode Exit fullscreen mode

To access the variable, a helper function would need to be created that returns the private variable.

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

var getPriv = func();
console.log(getPriv()); // => secret code
Enter fullscreen mode Exit fullscreen mode

🔗 Source: coderbyte.com

Q19: Explain the Prototype Design Pattern

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

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

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

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

🔗 Source: dofactory.com

Q20: Check if a given string is a isomorphic

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

For two strings to be isomorphic, all occurrences of a character in string A can be replaced with another character to get string B. The order of the characters must be preserved. There must be one-to-one mapping for ever char of string A to every char of string B.

  • paper and title would return true.
  • egg and sad would return false.
  • dgg and add would return true.
isIsomorphic("egg", 'add'); // true
isIsomorphic("paper", 'title'); // true
isIsomorphic("kick", 'side'); // false

function isIsomorphic(firstString, secondString) {

  // Check if the same lenght. 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;
}
Enter fullscreen mode Exit fullscreen mode

🔗 Source: https://github.com/kennymkchan

Q21: What does the term "Transpiling" stand for?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

There's no way to polyfill new syntax that has been added to the language. So the better option is to use a tool that converts your newer code into older code equivalents. This process is commonly called transpiling, a term for transforming + compiling.

Typically you insert the transpiler into your build process, similar to your code linter or your minifier.
There are quite a few great transpilers for you to choose from:

  • Babel: Transpiles ES6+ into ES5
  • Traceur: Transpiles ES6, ES7, and beyond into ES5

🔗 Source: You Don't Know JS, Up &going

Q22: How does the “this” keyword work? Provide some code examples.

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of.

Consider:

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
Enter fullscreen mode Exit fullscreen mode

🔗 Source: quirksmode.org

Q23: How would you add your own method to the Array object so the following code would work?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

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

JavaScript is not class based, but it is a prototype-based language. This means that each object is linked to another object, its prototype, and it inherits its methods. You can follow the prototype chain for each object up until you reach the null object which has no prototype. We need to add a method to the global Array object, and we will do this by modifying the Array prototype.

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
Enter fullscreen mode Exit fullscreen mode

🔗 Source: coderbyte.com

Q24: What is Hoisting in JavaScript?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

Hoisting is the JavaScript interpreter's action of moving all variable and function declarations to the top of the current scope. There are two types of hoisting:

  • variable hoisting - rare
  • function hoisting - more common

Wherever a var (or function declaration) appears inside a scope, that declaration is taken to belong to the entire scope and accessible everywhere throughout.

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
Enter fullscreen mode Exit fullscreen mode

🔗 Source: FullStack.Cafe

Q25: What will the following code output?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

0.1 + 0.2 === 0.3
Enter fullscreen mode Exit fullscreen mode

This will surprisingly output false because of floating point errors in internally representing certain numbers. 0.1 + 0.2 does not nicely come out to 0.3 but instead the result is actually 0.30000000000000004 because the computer cannot internally represent the correct number. One solution to get around this problem is to round the results when doing arithmetic with decimal numbers.

🔗 Source: coderbyte.com

Q26: Describe the Revealing Module Pattern design pattern

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐⭐

A variation of the module pattern is called the Revealing Module Pattern. The purpose is to maintain encapsulation and reveal certain variables and methods returned in an object literal. The direct implementation looks 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
Enter fullscreen mode Exit fullscreen mode

An obvious disadvantage of it is unable to reference the private methods

🔗 Source: scotch.io

Thanks 🙌 for reading and good luck on your interview!
Please share this article with your fellow devs if you like it!
Check more FullStack Interview Questions & Answers on 👉 www.fullstack.cafe

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player