Top 50 JavaScript Interview Questions: Answers & Tips for Success

50 popular JavaScript interview questions. These questions are frequently asked because they cover fundamental concepts, advanced techniques, and common JavaScript patterns that are essential for any developer working with this language.

By Vasyl Putra/
  1. What are the different data types in JavaScript?

JavaScript has seven primitive data types: String, Number, Boolean, Undefined, Null, Symbol, and BigInt. It also includes objects, which can be collections of data and more complex entities.

1
let name = "John"; // String
2
let age = 30; // Number
3
let isStudent = true; // Boolean
4
let address; // Undefined
5
let empty = null; // Null
6
let uniqueId = Symbol("id"); // Symbol
7
let bigIntNumber = BigInt(1234567890123456789012345678901234567890); // BigInt
8
let person = { name: "Jane", age: 25 }; // Object
  1. What is the difference between undefined and null?

undefined means a variable has been declared but not assigned a value, whereas null is an assignment value that represents the intentional absence of any object value.

1
let x;
2
console.log(x); //
3
let y = null;
4
console.log(y); // null
  1. What are JavaScript functions?

Functions are blocks of code designed to perform particular tasks. They are executed when they are called (invoked).

1
function greet(name) {
2
return `Hello, ${name}!`;
3
}
4
console.log(greet("Vasyl")); // Hello, Vasyl!
  1. Explain the difference between let, const, and var.

var is function-scoped or globally-scoped and can be re-declared and updated. let is block-scoped and can be updated but not re-declared. const is block-scoped and cannot be updated or re-declared.

1
var a = 1;
2
var a = 2; // No error
3
4
let b = 1;
5
// let b = 2; // Error: Identifier 'b' has already been declared
6
7
const c = 1;
8
// c = 2; // Error: Assignment to constant variable.
  1. What is a closure in JavaScript?

A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. Closures allow functions to access variables from an enclosing scope.

1
function outer() {
2
let counter = 0;
3
return function inner() {
4
counter++;
5
return counter;
6
};
7
}
8
const increment = outer();
9
console.log(increment()); // 1
10
console.log(increment()); // 2
  1. What is an Immediately Invoked Function Expression (IIFE)?

An IIFE is a function that runs as soon as it is defined. It is used to avoid polluting the global namespace and to create a new scope.

1
(function() {
2
console.log("IIFE executed!");
3
})();
  1. What is hoisting in JavaScript?

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope. This means that variables and function declarations can be used before they are declared.

1
console.log(x); //
2
var x = 5;
3
4
greet();
5
function greet() {
6
console.log("Hello!");
7
}
  1. What are arrow functions?

Arrow functions are a concise syntax for writing function expressions. They do not have their own this, arguments, super, or new.target.

1
const add = (a, b) => a + b;
2
console.log(add(2, 3)); // 5
  1. What is the difference between == and ===?

== checks for equality with type coercion, meaning it converts the operands to the same type before comparing. === checks for strict equality without type coercion, meaning the values and types must be the same.

1
console.log(1 == '1'); // true
2
console.log(1 === '1'); // false
  1. What is the purpose of the this keyword?

this refers to the object that is executing the current function. Its value depends on how the function is called.

1
const person = {
2
name: 'Vasyl',
3
greet: function() {
4
console.log(`Hello, my name is ${this.name}`);
5
}
6
};
7
person.greet(); // Hello, my name is Vasyl
  1. What is an event loop in JavaScript?

The event loop is a mechanism that allows JavaScript to perform non-blocking operations by offloading operations to the system kernel whenever possible.

1
console.log('Start');
2
setTimeout(() => {
3
console.log('Timeout');
4
}, 0);
5
console.log('End');
6
// Output: Start, End, Timeout
  1. What are Promises?

Promises are objects representing the eventual completion or failure of an asynchronous operation. They provide a way to handle asynchronous operations in a more readable manner.

1
const promise = new Promise((resolve, reject) => {
2
setTimeout(() => {
3
resolve('Done!');
4
}, 1000);
5
});
6
7
promise.then(result => {
8
console.log(result); // Done!
9
});
  1. Explain async and await.

async functions return a promise and allow the use of await within them. await pauses the execution of an async function and waits for the promise to resolve or reject.

1
async function fetchData() {
2
let response = await fetch('https://api.example.com/data');
3
let data = await response.json();
4
console.log(data);
5
}
6
fetchData();
  1. What is the DOM?

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content.

1
document.getElementById('myElement').textContent = 'Hello, World!';
  1. What is event delegation?

Event delegation is a technique of using a single event listener to manage all events of a particular type within a container. It takes advantage of event bubbling to handle events efficiently.

1
document.getElementById('parent').addEventListener('click', function(event) {
2
if (event.target && event.target.matches('button.class-name')) {
3
console.log('Button clicked');
4
}
5
});
  1. What is the difference between map, filter, and reduce?

map creates a new array with the results of calling a function on every element in the calling array. filter creates a new array with all elements that pass the test implemented by the provided function. reduce applies a function against an accumulator and each element in the array to reduce it to a single value.

1
const numbers = [1, 2, 3, 4, 5];
2
3
const doubled = numbers.map(n => n * 2);
4
console.log(doubled); // [2, 4, 6, 8, 10]
5
6
const even = numbers.filter(n => n % 2 === 0);
7
console.log(even); // [2, 4]
8
9
const sum = numbers.reduce((acc, n) => acc + n, 0);
10
console.log(sum); // 15
  1. What are higher-order functions?

Higher-order functions are functions that take other functions as arguments or return functions as their result. They are a key feature of functional programming.

1
function applyOperation(a, b, operation) {
2
return operation(a, b);
3
}
4
5
function add(x, y) {
6
return x + y;
7
}
8
9
console.log(applyOperation(5, 3, add)); // 8
  1. What is a callback function?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some action.

1
function fetchData(callback) {
2
setTimeout(() => {
3
const data = { name: 'John' };
4
callback(data);
5
}, 1000);
6
}
7
8
fetchData(data => {
9
console.log(data); // { name: 'John' }
10
});
  1. What are modules in JavaScript?

Modules are reusable pieces of code that can be imported and exported to organize and structure your code. They help to keep code clean, maintainable, and scoped properly.

1
// module.js
2
export const greet = name => `Hello, ${name}!`;
3
4
// main.js
5
import { greet } from './module.js';
6
console.log(greet('Vasyl')); // Hello, Vasyl!
  1. What is the purpose of use strict?

use strict is a directive that helps catch common coding errors and "unsafe" actions such as defining global variables. It enforces stricter parsing and error handling in your code.

1
'use strict';
2
x = 3.14; // Error: x is not defined
  1. What is the spread operator?

The spread operator (...) allows an iterable to expand in places where multiple arguments or elements are expected. It is used for copying arrays, merging arrays, and spreading elements.

1
const arr1 = [1, 2, 3];
2
const arr2 = [...arr1, 4, 5];
3
console.log(arr2); // [1, 2, 3, 4, 5]
4
5
const obj1 = { a: 1, b: 2 };
6
const obj2 = { ...obj1, c: 3 };
7
console.log(obj2); // { a: 1, b: 2, c: 3 }
  1. What are template literals?

Template literals are string literals allowing embedded expressions. They can be multi-line and use interpolation using ${} syntax.

1
const name = 'Vasyl';
2
const message = `Hello, ${name}!`;
3
console.log(message); // Hello, Vasyl!
  1. What is destructuring in JavaScript?

Destructuring is a syntax for extracting values from arrays or properties from objects into distinct variables.

1
const [a, b] = [1, 2];
2
console.log(a, b); // 1 2
3
4
const { name, age } = { name: 'Vasyl', age: 25 };
5
console.log(name, age); // Vasyl 25
  1. What is the difference between for...of and for...in?

for...of iterates over iterable objects (like arrays, strings, etc.) and returns the values. for...in iterates over the enumerable properties of an object and returns the keys.

1
const arr = [1, 2, 3];
2
for (const value of arr) {
3
console.log(value); // 1, 2, 3
4
}
5
6
const obj = { a: 1, b: 2 };
7
for (const key in obj) {
8
console.log(key); // a, b
9
}
  1. What are generators in JavaScript?

 Generators are functions that can be paused and resumed, producing a sequence of results using the function* syntax and yield keyword.

1
function* generateSequence() {
2
yield 1;
3
yield 2;
4
yield 3;
5
}
6
7
const generator = generateSequence();
8
console.log(generator.next().value); // 1
9
console.log(generator.next().value); // 2
10
console.log(generator.next().value); // 3
  1. What is the difference between synchronous and asynchronous code?

Synchronous code is executed line by line, with each operation waiting for the previous one to complete. Asynchronous code allows multiple operations to occur simultaneously, using callbacks, promises, or async/await.

1
console.log('Start');
2
setTimeout(() => {
3
console.log('Timeout');
4
}, 0);
5
console.log('End');
6
// Output: Start, End, Timeout
  1. What are JavaScript prototypes?

Prototypes are a mechanism by which JavaScript objects inherit features from one another. Every JavaScript object has a prototype, which is another object that the original object inherits properties and methods from.

1
function Person(name) {
2
this.name = name;
3
}
4
5
Person.prototype.greet = function() {
6
return `Hello, my name is ${this.name}`;
7
};
8
9
const person = new Person('Vasyl');
10
console.log(person.greet()); // Hello, my name is Vasyl
  1. What is event bubbling and capturing?

Event bubbling is when an event starts from the target element and propagates up to the root. Event capturing (or trickling) is the reverse, where the event starts from the root and propagates down to the target element.

1
document.getElementById('child').addEventListener('click', () => {
2
console.log('Child clicked');
3
});
4
5
document.getElementById('parent').addEventListener('click', () => {
6
console.log('Parent clicked');
7
});
8
// If you click on the child element, "Child clicked" and then "Parent clicked" will be logged.
  1. What is a promise chain?

A promise chain is a series of promises where each promise is executed after the previous one completes, using then() for chaining.

1
fetch('https://api.example.com/data')
2
.then(response => response.json())
3
.then(data => {
4
console.log(data);
5
return fetch('https://api.example.com/other-data');
6
})
7
.then(response => response.json())
8
.then(otherData => {
9
console.log(otherData);
10
})
11
.catch(error => {
12
console.error('Error:', error);
13
});
  1. What are JavaScript classes?

Classes are a template for creating objects and are a syntactical sugar over JavaScript's existing prototype-based inheritance. They provide a cleaner and more intuitive way to create objects and manage inheritance.

1
class Person {
2
constructor(name) {
3
this.name = name;
4
}
5
6
greet() {
7
return `Hello, my name is ${this.name}`;
8
}
9
}
10
11
const person = new Person('Vasyl');
12
console.log(person.greet()); // Hello, my name is Vasyl
  1. What is the super keyword?

The super keyword is used to call the constructor or methods of a parent class. It allows access to the parent class's properties and methods.

1
class Animal {
2
constructor(name) {
3
this.name = name;
4
}
5
6
speak() {
7
return `${this.name} makes a sound.`;
8
}
9
}
10
11
class Dog extends Animal {
12
constructor(name) {
13
super(name);
14
}
15
16
speak() {
17
return `${this.name} barks.`;
18
}
19
}
20
21
const dog = new Dog('Rex');
22
console.log(dog.speak()); // Rex barks.
  1. What are JavaScript Promises?

Promises represent the eventual completion or failure of an asynchronous operation. They are used to handle asynchronous operations more effectively, avoiding callback hell.

1
const promise = new Promise((resolve, reject) => {
2
setTimeout(() => {
3
resolve('Success!');
4
}, 1000);
5
});
6
7
promise.then(result => {
8
console.log(result); // Success!
9
}).catch(error => {
10
console.error(error);
11
});
  1. What is an async function?

An async function is a function declared with the async keyword that enables the use of the await keyword within it to pause execution until a promise is resolved.

1
async function fetchData() {
2
try {
3
let response = await fetch('https://api.example.com/data');
4
let data = await response.json();
5
console.log(data);
6
} catch (error) {
7
console.error('Error:', error);
8
}
9
}
10
11
fetchData();
  1. What is the new keyword?

The new keyword is used to create an instance of a constructor function or a class. It sets up the prototype chain and initializes the new object.

1
function Person(name) {
2
this.name = name;
3
}
4
5
const person = new Person('Vasyl');
6
console.log(person.name); // Vasyl
  1. What is the difference between call and apply?

Both call and apply invoke a function with a specified this value, but call takes arguments separately while apply takes arguments as an array.

1
function greet(greeting, punctuation) {
2
console.log(`${greeting}, my name is ${this.name}${punctuation}`);
3
}
4
5
const person = { name: 'Vasyl' };
6
7
greet.call(person, 'Hello', '!'); // Hello, my name is Vasyl!
8
greet.apply(person, ['Hi', '.']); // Hi, my name is Vasyl.
  1. What is the bind method?

The bind method creates a new function that, when called, has its this value set to the provided value, with a given sequence of arguments.

1
const person = {
2
name: 'Vasyl',
3
greet() {
4
console.log(`Hello, my name is ${this.name}`);
5
}
6
};
7
8
const greet = person.greet.bind(person);
9
greet(); // Hello, my name is Vasyl
  1. What is the this keyword in JavaScript?

this refers to the object that is executing the current function. Its value is determined by how the function is called.

1
const person = {
2
name: 'Vasyl',
3
greet() {
4
console.log(`Hello, my name is ${this.name}`);
5
}
6
};
7
8
person.greet(); // Hello, my name is Vasyl
9
10
const greet = person.greet;
11
greet(); // , since `this` refers to the global object (or undefined in strict mode)
  1. What is the difference between == and ===?

== compares values for equality with type coercion, whereas === compares values for equality without type coercion.

1
console.log(1 == '1'); // true
2
console.log(1 === '1'); // false
  1. What is an arrow function in JavaScript?

An arrow function is a shorter syntax for writing function expressions. They do not have their own this, arguments, super, or new.target.

1
const add = (a, b) => a + b;
2
console.log(add(2, 2)); // 4
  1. What is the fetch API?

The fetch API is a modern interface for making HTTP requests, replacing older technologies like XMLHttpRequest. It returns a promise that resolves to the response of the request.

1
fetch('https://api.example.com/data')
2
.then(response => response.json())
3
.then(data => console.log(data))
4
.catch(error => console.error('Error:', error));
  1. What is the typeof operator?

The typeof operator returns a string indicating the type of the operand. It is used to determine the type of a variable or value.

1
console.log(typeof 'hello'); // string
2
console.log(typeof 42); // number
3
console.log(typeof true); // boolean
4
console.log(typeof ); // undefined
5
console.log(typeof { a: 1 }); // object
6
console.log(typeof null); // object (this is a known bug in JavaScript)
7
console.log(typeof function() {}); // function
  1. What are JavaScript events?

Events are actions or occurrences that happen in the browser, which can be detected and handled using JavaScript. Examples include clicking a button, loading a page, and submitting a form.

1
document.getElementById('myButton').addEventListener('click', () => {
2
console.log('Button clicked');
3
});
  1. What is the Date object in JavaScript?

The Date object is used for working with dates and times in JavaScript. It provides methods to get and set the year, month, day, hour, minute, second, and millisecond.

1
const now = new Date();
2
console.log(now); // Current date and time
3
4
const specificDate = new Date('2024-07-02');
5
console.log(specificDate); // July 2, 2024
  1. What is the setTimeout function?

setTimeout is a function that sets a timer to execute a function or code snippet after a specified delay in milliseconds.

1
setTimeout(() => {
2
console.log('This message is delayed by 2 seconds');
3
}, 2000);
  1. What is the setInterval function?

setInterval is a function that repeatedly calls a function or code snippet with a fixed time delay between each call, specified in milliseconds.

1
const intervalId = setInterval(() => {
2
console.log('This message repeats every 2 seconds');
3
}, 2000);
4
5
// To stop the interval
6
clearInterval(intervalId);
  1. What is a promise in JavaScript?

A promise is an object representing the eventual completion or failure of an asynchronous operation. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.

1
const promise = new Promise((resolve, reject) => {
2
setTimeout(() => {
3
resolve('Success!');
4
}, 1000);
5
});
6
7
promise.then(result => {
8
console.log(result); // Success!
9
}).catch(error => {
10
console.error(error);
11
});
  1. What is the async/await syntax?

async/await is syntactic sugar built on top of promises, allowing you to write asynchronous code in a synchronous-looking manner. An async function returns a promise, and await pauses the execution of the function until the promise is resolved.

1
async function fetchData() {
2
try {
3
const response = await fetch('https://api.example.com/data');
4
const data = await response.json();
5
console.log(data);
6
} catch (error) {
7
console.error('Error:', error);
8
}
9
}
10
11
fetchData();
  1. What are JavaScript cookies?

Cookies are small pieces of data stored on the user's computer by the web browser. They are used to remember information about the user between page requests.

1
// Setting a cookie
2
document.cookie = 'username=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT';
3
4
// Getting a cookie
5
const cookies = document.cookie.split('; ');
6
const usernameCookie = cookies.find(cookie => cookie.startsWith('username='));
7
const username = usernameCookie.split('=')[1];
8
console.log(username); // John
  1. What is the scope?

Scope determines the visibility and accessibility of variables and functions during runtime. Understanding scope is crucial for managing variable lifetimes, avoiding naming conflicts, and writing maintainable code. There are two main types of scope in JavaScript: global scope and local scope.

Global Scope

Variables declared outside of any function or block have global scope. They can be accessed from anywhere within the script, including inside functions and blocks.

1
// Global scope
2
let message = "Hello, world!";
3
4
function greet() {
5
console.log(message); // Accessible within the function
6
}
7
8
greet(); // Outputs: Hello, world!
9
console.log(message); // Outputs: Hello, world!

In this example, message is declared outside any function, making it globally scoped. Both the greet function and the console.log statement outside the function can access and modify message.

Local Scope

Variables declared within a function or block have local scope. They are only accessible within that specific function or block.

1
function greet() {
2
// Local scope
3
let name = "Vasyl";
4
console.log(`Hello, ${name}!`);
5
}
6
7
greet(); // Outputs: Hello, Vasyl!
8
console.log(name); // Throws ReferenceError: name is not defined

In this example, name is declared inside the greet function, making it locally scoped. It cannot be accessed outside of the function.

Block Scope (ES6+)

Introduced in ECMAScript 6 (ES6), block scope refers to the visibility of variables within any block delimited by curly braces { }, such as if, for, while, and switch statements.

1
function calculate() {
2
let result = 0;
3
4
if (true) {
5
// Block scope
6
let x = 10;
7
result = x * 2;
8
}
9
10
console.log(result); // Outputs: 20
11
console.log(x); // Throws ReferenceError: x is not defined
12
}
13
14
calculate();

In this example, x is declared inside the if block and is only accessible within that block due to block scoping. The result variable, declared outside the block, retains its value after the block executes.

Lexical Scope

Lexical scope means that the scope of a variable is determined by its position within the source code. In JavaScript, functions are executed using the scope chain that was in effect when they were defined, not when they are executed.

1
function outerFunction() {
2
let outerVar = 'I am outside!';
3
4
function innerFunction() {
5
let innerVar = 'I am inside!';
6
console.log(outerVar); // Can access outerVar
7
}
8
9
innerFunction();
10
console.log(innerVar); // Throws ReferenceError: innerVar is not defined
11
}
12
13
outerFunction();

In this example, innerFunction can access outerVar defined in its outer scope due to lexical scoping. However, innerVar defined inside innerFunction cannot be accessed outside its scope.

  1. What is the Memoization?

Memoization is a technique used in programming to optimize functions by caching the results of expensive function calls and returning the cached result when the same inputs occur again. This can significantly improve performance by avoiding redundant computations.

How Memoization Works

When a function is memoized, it stores the results of expensive function calls and returns the cached result when the same inputs occur again. This caching mechanism typically uses an object (often called a cache) where the function stores the computed results indexed by the function arguments.

Benefits of Memoization

  • Performance Improvement: Memoization can drastically reduce the time complexity of functions that are called frequently with the same inputs.
  • Reduced Recalculation: By storing previously computed results, memoization eliminates redundant computations, especially in recursive or computationally intensive functions.

Example of Memoization in JavaScript

Here's a basic example of how memoization can be implemented in JavaScript using a higher-order function:

1
// Function to calculate Fibonacci numbers (not optimized)
2
function fibonacci(n) {
3
if (n <= 1) return n;
4
return fibonacci(n - 1) + fibonacci(n - 2);
5
}
6
7
// Memoization function decorator
8
function memoize(fn) {
9
const cache = {};
10
return function(...args) {
11
const key = JSON.stringify(args);
12
if (cache[key] === ) {
13
cache[key] = fn.apply(this, args);
14
}
15
return cache[key];
16
};
17
}
18
19
// Applying memoization to fibonacci function
20
const memoizedFibonacci = memoize(fibonacci);
21
22
console.log(memoizedFibonacci(10)); // Outputs: 55
23
console.log(memoizedFibonacci(10)); // Outputs: 55 (cached result)
  • Original Fibonacci Function: fibonacci calculates Fibonacci numbers recursively.
  • Memoization Function (memoize): memoize takes a function fn and returns a new function that caches results.
  • Caching Mechanism: The cache object stores results indexed by the function arguments converted to a string (JSON.stringify(args)).
  • Memoized Fibonacci: memoizedFibonacci is the memoized version of fibonacci, created using memoize.
  • Usage: When memoizedFibonacci(10) is called the first time, it computes and caches the result (55). Subsequent calls with the same argument (10) return the cached result without recomputation.

Use Cases for Memoization

  • Recursive Functions: Memoization is commonly used with recursive functions like Fibonacci, factorial calculations, or recursive traversal algorithms to optimize performance.
  • Expensive Computations: Functions that involve complex calculations, database queries, or API requests can benefit from memoization to avoid repeated expensive operations.
By a coffee for Puvvl

Keep Updated

Stay ahead of the curve with Puvvl.dev! Join our mailing list to receive exclusive, handpicked updates and important news. Be the first to know about our latest advancements and innovations.