Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

Top 20 JavaScript Technical Questions in Coding Interviews

Introduction

Coding interviews can be a nerve-wracking experience, especially for those who are relatively new to programming. JavaScript is one of the most popular programming languages and is often used in coding interviews. In this article, we will discuss the top 20 JavaScript technical questions that you may encounter in a coding interview. We will provide you with the formal interview question, the relevant code examples, and some intuition and analogies to help you understand the concepts better.

1. What is the difference between == and === in JavaScript?

Interview Question: Explain the difference between == (loose equality) and === (strict equality) in JavaScript.

Answer: In JavaScript, == (loose equality) compares two values and returns true if they are equal, allowing type coercion. On the other hand, === (strict equality) checks if the two values are equal and have the same type, without allowing type coercion.

Code Examples:

console.log(1 == "1"); // true, because after type coercion, the values are equal
console.log(1 === "1"); // false, because the types are different (number vs. string)

Intuition: Think of == as a more lenient comparison, trying to find common ground between the two values, whereas === is strict and requires both the value and type to match.

2. What is a closure in JavaScript?

Interview Question: Explain the concept of a closure in JavaScript and provide an example.

Answer: A closure is a function that has access to its own scope, the scope of the outer function, and the global scope. It is created when a nested function references a variable from its containing function.

Code Example:

function outerFunction() {
  var outerVariable = "I am outside!";

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

var closureFunction = outerFunction();
closureFunction(); // Output: "I am outside!"

Intuition: Imagine a closure as a backpack that a function carries around. This backpack contains all the variables that the function needs from its outer scope, even after the outer function has completed execution.

3. What is hoisting in JavaScript?

Interview Question: Explain the concept of hoisting in JavaScript and provide an example.

Answer: Hoisting is a mechanism in JavaScript where variable and function declarations are moved to the top of their containing scope during the compilation phase. However, only the declarations are hoisted, not the initializations.

Code Example:

console.log(hoistedVar); // Output: undefined
var hoistedVar = "I am hoisted!";

// Equivalent to:
var hoistedVar;
console.log(hoistedVar);
hoistedVar = "I am hoisted!";

Intuition: Think of hoisting as the JavaScript engine organizing your code by moving all the declarations to the top, allowing you to use variables and functions before they are declared in the code.

4. What is the difference between null and undefined in JavaScript?

Interview Question: Explain the difference between null and undefined in JavaScript.

Answer: In JavaScript, null is an assignment value that represents no value or no object. It is an intentional absence of any object value. On the other hand, undefined is a type itself and represents a variable that has been declared but has not yet been assigned a value.

Code Examples:

var nullVar = null;
console.log(nullVar); // Output: null

var undefinedVar;
console.log(undefinedVar); // Output: undefined

Intuition: You can think of null as an explicit "nothing" you can assign to a variable, while undefined is what you get when a variable has been declared without an assigned value.

5. What is the difference between let, const, and var in JavaScript?

Interview Question: Explain the difference between let, const, and var in JavaScript and provide examples.

Answer: In JavaScript, let, const, and var are used to declare variables. var is function-scoped and has been the traditional way of declaring variables. let and const are block-scoped, and they were introduced in ECMAScript 2015 (ES6).

let allows you to declare a variable that can be reassigned, while const is used to declare a variable that cannot be reassigned.

Code Examples:

var functionScopedVar = "I am function-scoped!";
let blockScopedVar = "I am block-scoped!";
const constantVar = "I am a constant!";

if (true) {
  var functionScopedVar = "I am still function-scoped!";
  let blockScopedVar = "I am still block-scoped!";
  // const constantVar = "I cannot be reassigned!"; // Would throw an error
}

console.log(functionScopedVar); // Output: "I am still function-scoped!"
console.log(blockScopedVar); // Output: "I am block-scoped!"
console.log(constantVar); // Output: "I am a constant!"

Intuition: Think of var as a more flexible way of declaring variables that can be accessed within the entire function scope. In contrast, let and const provide better control over variable scope, reducing the chances of bugs caused by unintentional modifications.

6. What are the different ways to create an object in JavaScript?

Interview Question: Explain the different ways to create an object in JavaScript and provide examples.

Answer: In JavaScript, there are several ways to create an object:

  1. Object literal
  2. Constructor function
  3. Object.create() method
  4. ES6 class

Code Examples:

// 1. Object literal
const objLiteral = {
  key: "value",
};

// 2. Constructor function
function ConstructorFunction() {
  this.key = "value";
}
const objConstructor = new ConstructorFunction();

// 3. Object.create() method
const objCreate = Object.create(null);
objCreate.key = "value";

// 4. ES6 class
class ES6Class {
  constructor() {
    this.key = "value";
  }
}
const objClass = new ES6Class();

Intuition: Creating objects in JavaScript is like building a house using different blueprints or techniques. Each method has its own advantages and use cases, but ultimately, they serve the same purpose – creating an object.

7. What is an Immediately Invoked Function Expression (IIFE) in JavaScript?

Interview Question: Explain the concept of an Immediately Invoked Function Expression (IIFE) in JavaScript and provide an example.

Answer: An Immediately Invoked Function Expression (IIFE) is a function that is defined and executed immediately after its creation. It is a design pattern that allows creating a new scope, making sure that variables defined inside the IIFE don't pollute the global scope.

Code Example:

(function () {
  var iifeVar = "I am inside an IIFE!";
  console.log(iifeVar);
})(); // Output: "I am inside an IIFE!"

// console.log(iifeVar); // Would throw a ReferenceError, as iifeVar is not accessible in the global scope

Intuition: Think of an IIFE as a self-contained environment that keeps your code organized and prevents variables from leaking into the global scope.

8. What is the difference between call, apply, and bind in JavaScript?

Interview Question: Explain the difference between call, apply, and bind in JavaScript and provide examples.

Answer: In JavaScript, call, apply, and bind are methods used to control the this context inside a function.

call and apply are similar in that they allow you to invoke a function with a specific this context and arguments. The difference between them is how the arguments are passed: call accepts arguments as a comma-separated list, while apply takes an array of arguments.

bind, on the other hand, creates a new function with a specific this context and optional, pre-specified arguments. The new function can be invoked later with additional arguments.

Code Examples:

function greet(greeting, punctuation) {
  console.log(greeting + ", " + this.name + punctuation);
}

const person = {
  name: "Alice",
};

// Using call
greet.call(person, "Hello", "!"); // Output: "Hello, Alice!"

// Using apply
greet.apply(person, ["Hello", "!"]); // Output: "Hello, Alice!"

// Using bind
const boundGreet = greet.bind(person, "Hello");
boundGreet("!"); // Output: "Hello, Alice!"

Intuition: Imagine you're a director giving instructions to actors (call, apply) or delegating tasks to assistants (bind). You're controlling who gets to perform the actions and how they should do it.

9. What is the difference between event bubbling and event capturing in JavaScript?

Interview Question: Explain the difference between event bubbling and event capturingExplanation: Event bubbling and event capturing are two different ways in which JavaScript handles event propagation. Event propagation is the process of determining which elements should receive an event when it is triggered. Both event bubbling and event capturing occur in three phases: target, capturing, and bubbling.

In event bubbling, the event starts at the target element and then moves up the DOM tree, notifying each ancestor element of the event. This is the default behavior in JavaScript.

In event capturing, the event starts at the top of the DOM tree and moves down to the target element, notifying each ancestor element on the way.

Code Example:

<!DOCTYPE html>
<html>
<head>
<style>
  div {
    padding: 15px;
    border: 1px solid black;
  }
</style>
</head>
<body>

<div id="grandparent">
  Grandparent
  <div id="parent">
    Parent
    <div id="child">
      Child
    </div>
  </div>
</div>

<script>
  function logEvent(event) {
    console.log(event.target.id + " - " + event.currentTarget.id);
  }

  document.getElementById("grandparent").addEventListener("click", logEvent, true); // Capturing
  document.getElementById("parent").addEventListener("click", logEvent, true); // Capturing
  document.getElementById("child").addEventListener("click", logEvent, true); // Capturing

  document.getElementById("grandparent").addEventListener("click", logEvent, false); // Bubbling
  document.getElementById("parent").addEventListener("click", logEvent, false); // Bubbling
  document.getElementById("child").addEventListener("click", logEvent, false); // Bubbling
</script>

</body>
</html>

Intuition: Imagine a family gathering where the child spills a drink. In event bubbling, the child tells their parent, who tells their parent (the grandparent), and so on. In event capturing, the grandparent notices the spill first, then tells the parent, who finally tells the child.

10. How does JavaScript handle asynchronous operations?

Interview Question: Explain how JavaScript handles asynchronous operations and provide an example.

Explanation: JavaScript is single-threaded, which means it can only execute one task at a time. To handle asynchronous operations, JavaScript uses the event loop, callback queue, and Web APIs. When an asynchronous task is encountered, it is offloaded to a Web API which executes the task. Once the task is complete, the Web API pushes a callback function to the callback queue. The event loop continually checks if the call stack is empty, and when it is, it takes the first callback function from the callback queue and pushes it onto the call stack for execution.

Code Example:

console.log("Start");

setTimeout(function() {
  console.log("Async operation");
}, 0);

console.log("End");

Intuition: Imagine a restaurant where the chef (JavaScript) can only cook one dish at a time. When an order is placed, a waiter (Web API) takes the order and starts preparing it. Once the dish is ready, the waiter places it in the pickup area (callback queue). The chef keeps an eye on the pickup area (event loop) and picks up the dish only when they have finished cooking the current dish (call stack is empty).

11. What is a Promise in JavaScript?

Interview Question: Explain what a Promise is in JavaScript and provide an example of using a Promise.

Explanation: A Promise in JavaScript represents the eventual result of an asynchronous operation. It is an object that may produce a single value at some point in the future. A Promise is in one of three states:

  1. Pending: The initial state; neither fulfilled nor rejected.
  2. Fulfilled: The operation completed successfully, and the Promise has a resulting value.
  3. Rejected: The operation failed, and the Promise has a reason for the failure.

A Promise is said to be "settled" if it is either fulfilled or rejected.

Code Example:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Promise resolved");
  }, 1000);
});

myPromise.then((message) => {
  console.log(message);
}).catch((error) => {
  console.log(error);
});

Intuition: Think of a Promise as a contract between two parties. One party promises to deliver a result in the future (resolve) or provide a reason why they couldn't (reject). The other party can then decide what to do based on whether the promise was fulfilled or rejected.

12. What is async/await in JavaScript?

Interview Question: Explain the async/await syntax in JavaScript and provide an example.

Explanation: The async/await syntax is a way to write asynchronous code that looks and behaves like synchronous code. It is built on top of Promises and provides a more readable and concise way to write asynchronous code. An async function returns a Promise. The await keyword can only be used inside an async function and is used to wait for a Promise to resolve or reject before continuing the execution of the function.

Code Example:

async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}

fetchData();

Intuition: Imagine you're at a coffee shop and you place an order for a coffee. You don't want to stand there waiting for your coffee to be ready, blocking other customers from placing their orders. Instead, you wait for the barista to call your name (await) and continue with other tasks (async) until your coffee is ready.

13. What is a callback function in JavaScript?

Interview Question: Explain what a callback function is in JavaScript and provide an example.

Explanation: A callback function is a function that is passed as an argument to another function and is executed after the completion of some operation. Callback functions are used to handle asynchronous operations, maintain control flow, and support functional programming patterns.

Code Example:

function greeting(name, callback) {
  console.log("Hello, " + name);
  callback();
}

function sayGoodbye() {
  console.log("Goodbye!");
}

greeting("John", sayGoodbye);

Intuition: Think of a callback function as a way to delegate tasks. When you pass a callback function to another function, you're telling it, "Once you're done with your task, execute this function next."

14. What are Arrow functions in JavaScript?

Interview Question: Explain what arrow functions are in JavaScript and provide an example.

Explanation: Arrow functions, introduced in ECMAScript 6 (ES6), are a more concise way of writing function expressions in JavaScript. They do not have their own this value, arguments object, or super, and they cannot be used as constructors. Arrow functions are particularly useful when writing callbacks or functional programming patterns.

Code Example:

const add = (a, b) => a + b;

console.log(add(1, 2)); // Output: 3

Intuition: Imagine a function as a machine that takes input, processes it, and produces output. Arrow functions are like streamlined versions of these machines, with a more compact and efficient design, but without some of the extra features (e.g., this, arguments, super).

15. What is the this keyword in JavaScript?

Interview Question: Explain what the this keyword is in JavaScript and provide an example.

Explanation: The this keyword in JavaScript is a reference to the current execution context. It is used to access the properties and methods of the object on which the function is called. The value of this depends on how the function is called and can have different values in different scenarios, such as in a global context, an object method, a constructor, or an event handler.

Code Example:

const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

console.log(person.fullName()); // Output: John Doe

Intuition: Think of the this keyword as a way for a function to refer to the object it belongs to or the context in which it is called. In the example above, this allows the fullName function to access the firstName and lastName properties of the person object.

16. What is the Prototype in JavaScript?

Interview Question: Explain what the Prototype is in JavaScript and provide an example.

Explanation: The Prototype in JavaScript is a mechanism that allows objects to share properties and methods. Every object in JavaScript has a hidden property called [[Prototype]] (also accessible through __proto__ or the Object.getPrototypeOf method) that points to its prototype object. When a property or method is accessed on an object and is not found, JavaScript looks up the prototype chain to find it. This chain continues until the property or method is found or the end of the chain is reached.

Code Example:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

Person.prototype.fullName = function() {
  return this.firstName + " " + this.lastName;
}

const john = new Person("John", "Doe");
console.log(john.fullName()); // Output: John Doe

Intuition: Think of the prototype as a shared storage space for objects. When an object needs a property or method that it doesn't have, it can look in this shared space to find it.

17. What is the difference between Array.map() and Array.forEach() in JavaScript?

Interview Question: Explain the difference between Array.map() and Array.forEach() in JavaScript and provide an example.

Explanation: Both Array.map() and Array.forEach() are used to iterate over an array in JavaScript, but they have different purposes and return values.

Array.map(): Creates a new array by applying a callback function to each element in the original array. The callback function takes three arguments: the current element, the index of the current element, and the array being processed. The length of the new array will be the same as the original array.

Array.forEach(): Executes a callback function for each element in the array, but does not create a new array or change the original array. The callback function takes the same three arguments as in Array.map().

Code Example:

const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map((number) => {
  return number * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]

numbers.forEach((number) => {
  console.log(number * 2);
});
// Output:
// 2
// 4
// 6
// 8
// 10

Intuition: Think of Array.map() as a factory that takes an array as input, processes each element, and produces a new array as output. On the other hand, Array.forEach() is like a supervisor who checks on each element in the array, but doesn't produce anything new.

18. What is a JavaScript Generator?

Interview Question: Explain what a JavaScript Generator is and provide an example.

Explanation: A Generator is a special type of function in JavaScript that can be paused and resumed during execution. Generators are defined using the function* syntax and use the yield keyword to pause their execution. When a generator is called, it returns a generator object, which can be used to control the generator's execution using the next() method.

Code Example:

function* idGenerator() {
  let id = 1;
  while (true) {
    yield id++;
  }
}

const gen = idGenerator();
console.log(gen.next().value); // Output: 1
console.log(gen.next().value); // Output: 2
console.log(gen.next().value); // Output: 3

Intuition: Think of a generator as a machine that produces a series of values, but can be paused in between values to perform other tasks. In the example above, the idGenerator is a generator that produces an infinite series of IDs, but can be paused after each ID is produced.

19. What are JavaScript Modules?

Interview Question: Explain what JavaScript Modules are and provide an example.

Explanation: JavaScript Modules are a way to organize and encapsulate code into reusable pieces. They allow developers to create, export, and import code between different files and namespaces. Modules help to keep the global scope clean, promote code reuse and separation of concerns, and make it easier to manage large codebases.

In JavaScript, there are two module systems:

  1. CommonJS (used in Node.js): Uses require() to import modules and module.exports or exports to export modules.
  2. ES6 Modules (used in modern browsers): Uses the import keyword to import modules and the export keyword to export modules.

Code Example (CommonJS):

// math.js
module.exports.add = (a, b) => a + b;

// app.js
const math = require('./math');
console.log(math.add(1, 2)); // Output: 3

Code Example (ES6 Modules):

// math.js
export const add = (a, b) => a + b;

// app.js
import { add } from './math.js';
console.log(add(1, 2)); // Output: 3

Intuition: Think of JavaScript modules as a way to package code into containers that can be transported and used in different parts of the application. It's like having a set of tools that you can pick and choose from when working on a project.

20. What is the instanceof operator in JavaScript?

Interview Question: Explain what the instanceof operator is in JavaScript and provide an example.

Explanation: The instanceof operator in JavaScript is used to check if an object is an instance of a particular constructor or class. It returns true if the object's prototype chain contains the prototype property of the constructor or class, and false otherwise.

Code Example:

function Person(name) {
  this.name = name;
}

const john = new Person("John");

console.log(john instanceof Person); // Output: true
console.log(john instanceof Object); // Output: true
console.log(john instanceof Array); // Output: false

Intuition: Think of the instanceof operator as a way to verify the ancestry of an object. It's like checking if an object has a specific prototype in its lineage.

Conclusion

In this article, we have covered the top 20 JavaScript technical questions that are frequently asked in coding interviews. By understanding these concepts and practicing the code examples, you will be better prepared for your next JavaScript interview. Good luck!