Top 26 JavaScript Interview Questions I Wish I Knew
Tags: javascript, interview, fullstack, career
Published: 2018-09-24 01:40:39

---
title: Top 26 JavaScript Interview Questions I Wish I Knew
published: true
description: Top 26 JavaScript Interview Questions You Wish You Knew
tags: #javascript #interview #fullstack #career 
canonical_url: https://www.fullstack.cafe/blog/top-26-javascript-interview-questions-and-answers-in-2019
---
![Top 26 JavaScript Interview Questions I Wish I Knew](https://images.pexels.com/photos/697662/pexels-photo-697662.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940)
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](https://www.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](https://www.fullstack.cafe/?utm_source=dev&utm_medium=blog)

### Q1: What is Coercion in JavaScript?
> Topic: **JavaScript**<br/>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:
```js
var a = "42";

var b = Number( a );

a;				// "42"
b;				// 42 -- the number!
```
And here's an example of implicit coercion:
```js
var a = "42";

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

a;				// "42"
b;				// 42 -- the number!
``` 

🔗 **Source:** [FullStack.Cafe](https://www.fullstack.cafe)
### Q2: What is Scope in JavaScript?
> Topic: **JavaScript**<br/>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](https://www.fullstack.cafe)
### Q3: Explain equality in JavaScript
> Topic: **JavaScript**<br/>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

```js
var a = "42";
var b = 42;

a == b;			// true
a === b;		// false
```
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](https://www.fullstack.cafe)
### Q4: Explain what a callback function is and provide a simple example.
> Topic: **JavaScript**<br/>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.

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

🔗 **Source:** [coderbyte.com](https://coderbyte.com/algorithm/10-common-javascript-interview-questions)
### Q5: What does "use strict" do?
> Topic: **JavaScript**<br/>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:

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

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:

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

🔗 **Source:** [coderbyte.com](https://coderbyte.com/algorithm/10-common-javascript-interview-questions)
### Q6: Explain Null and Undefined in JavaScript
> Topic: **JavaScript**<br/>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](https://www.fullstack.cafe)
### Q7: Write a function that would allow you to do this.
> Topic: **JavaScript**<br/>Difficulty: ⭐⭐

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

---
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`.

```js
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);
```

🔗 **Source:** [coderbyte.com](https://coderbyte.com/algorithm/3-common-javascript-closure-questions)
### Q8: Explain Values and Types in JavaScript
> Topic: **JavaScript**<br/>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](https://www.fullstack.cafe)
### Q9: Explain event bubbling and how one may prevent it
> Topic: **JavaScript**<br/>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](https://github.com/kennymkchan/interview-questions-in-javascript)
### Q10: What is let keyword in JavaScript?
> Topic: **JavaScript**<br/>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](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md)
### Q11: How would you check if a number is an integer?
> Topic: **JavaScript**<br/>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.

```js
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](https://coderbyte.com/algorithm/10-common-javascript-interview-questions)
### Q12: What is IIFEs (Immediately Invoked Function Expressions)?
> Topic: **JavaScript**<br/>Difficulty: ⭐⭐⭐

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created:
```js
(function IIFE(){
	console.log( "Hello!" );
})();
// "Hello!"
```

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](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript)
### Q13: How to compare two objects in JavaScript?
> Topic: **JavaScript**<br/>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:

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

a == c;		// true
b == c;		// true
a == b;		// false
```
For *deep object comparison* use external libs like `deep-equal` or implement your own recursive equality algorithm.


🔗 **Source:** [FullStack.Cafe](https://www.fullstack.cafe)
### Q14: Could you explain the difference between ES5 and ES6
> Topic: **JavaScript**<br/>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**:<br/>
Consider:
```js
const greetings = (name) => {
      return `hello ${name}`;
}
```
and even:
```js
const greetings = name => `hello ${name}`;
```
* **Const**. <br>
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.
```js
const NAMES = [];
NAMES.push("Jim");
console.log(NAMES.length === 1); // true
NAMES = ["Steve", "John"]; // error
```
* **Block-scoped variables**.<br>
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.
```js
// Basic syntax
function multiply (a, b = 2) {
     return a * b;
}
multiply(5); // 10
```
* **Class Definition and Inheritance**<br>
ES6 introduces language support for classes (`class` keyword), constructors (`constructor` keyword), and the `extend` keyword for inheritance.

* **for-of operator**<br>
The for...of statement creates a loop iterating over iterable objects.
* **Spread Operator**
For objects merging
```js
const obj1 = { a: 1, b: 2 }
const obj2 = { a: 2, c: 3, d: 4}
const obj3 = {...obj1, ...obj2}
```
* **Promises**<br>
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. 
```js
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')
 })
```
* **Modules exporting & importing**
Consider module exporting:
```js
const myModule = { x: 1, y: () => { console.log('This is ES5') }}
export default myModule;
```
and importing:
```js
import myModule from './myModule';
```


🔗 **Source:** [Bulby.io](undefined)
### Q15: Explain the difference between "undefined" and "not defined" in JavaScript
> Topic: **JavaScript**<br/>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.

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

`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`.

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

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

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

🔗 **Source:** [stackoverflow.com](http://stackoverflow.com/questions/20822022/javascript-variable-definition-declaration)
### Q16: What is the difference between anonymous and named functions? 
> Topic: **JavaScript**<br/>Difficulty: ⭐⭐⭐

Consider:
```js
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();
```

🔗 **Source:** [FullStack.Cafe](https://www.fullstack.cafe)
### Q17: What is “closure” in javascript? Provide an example?
> Topic: **JavaScript**<br/>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

```javascript
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
```

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

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

🔗 **Source:** [github.com/ganqqwerty](https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Question/blob/master/README.md)
### Q18: How would you create a private variable in JavaScript?
> Topic: **JavaScript**<br/>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:

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

console.log(priv); // throws error
```

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

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

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

🔗 **Source:** [coderbyte.com](https://coderbyte.com/algorithm/10-common-javascript-interview-questions)
### Q19: Explain the Prototype Design Pattern
> Topic: **JavaScript**<br/>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](http://www.dofactory.com/javascript/prototype-design-pattern)
### Q20: Check if a given string is a isomorphic
> Topic: **JavaScript**<br/>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.

```js
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;
}
```

🔗 **Source:** [https://github.com/kennymkchan](https://github.com/kennymkchan/interview-questions-in-javascript)
### Q21: What does the term "Transpiling" stand for?
> Topic: **JavaScript**<br/>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](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md)
### Q22: How does the “this” keyword work? Provide some code examples.
> Topic: **JavaScript**<br/>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:
```js
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](https://www.quirksmode.org/js/this.html)
### Q23: How would you add your own method to the Array object so the following code would work?
> Topic: **JavaScript**<br/>Difficulty: ⭐⭐⭐⭐

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

---
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`.

```js
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](https://coderbyte.com/algorithm/10-common-javascript-interview-questions)
### Q24: What is Hoisting in JavaScript?
> Topic: **JavaScript**<br/>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.

```js
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
```


🔗 **Source:** [FullStack.Cafe](https://www.fullstack.cafe)
### Q25: What will the following code output?
> Topic: **JavaScript**<br/>Difficulty: ⭐⭐⭐⭐

```js
0.1 + 0.2 === 0.3
```

---
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](https://coderbyte.com/algorithm/10-common-javascript-interview-questions)
### Q26: Describe the Revealing Module Pattern design pattern
> Topic: **JavaScript**<br/>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:

```js
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
```
An obvious disadvantage of it is unable to reference the private methods

🔗 **Source:** [scotch.io](https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know)

> *Thanks 🙌 for reading and good luck on your interview!* <br/>*Please share this article with your fellow devs if you like it!* <br/>*Check more FullStack Interview Questions & Answers on 👉 [www.fullstack.cafe](https://www.fullstack.cafe)*