Top 80+ JavaScript Interview Questions and Answers Cheat Sheet (2024)
This post covers the top 80+ JavaScript interview questions and answers for 2024. From beginner to advanced levels, these questions will help you sharpen your JavaScript skills and ace your next interview.
- What is JavaScript?
JavaScript is a lightweight, interpreted programming language commonly used for making web pages interactive. - Difference between JavaScript and Java?
JavaScript is an interpreted, client-side scripting language, whereas Java is a compiled, server-side programming language. - What are the data types in JavaScript?
- Primitive: String, Number, Boolean, Undefined, Null, Symbol, BigInt
- Non-Primitive: Object, Array, Function
- What are the features of JavaScript?
- Lightweight and interpreted
- Cross-platform
- Object-oriented
- Asynchronous and event-driven
- Advantages of JavaScript?
- Client-side execution for faster user interactions
- Rich interface elements like drag-and-drop
- Extensively supported by frameworks and libraries
- How do you create an object in JavaScript?
const obj = { name: 'John', age: 25 };
- How do you create an array in JavaScript?
const arr = [1, 2, 3];
- Built-in methods in JavaScript?
push()
: Adds element to an arraypop()
: Removes last elementconcat()
: Merges arrayslength()
: Returns array lengthDate()
: Gets current date
- What is the scope of a variable?
- Global scope: Variables accessible anywhere
- Local scope: Variables accessible only within a function or block
- What is ‘this’ in JavaScript?
Thethis
keyword refers to the current object in which the code is executing. - How are variables declared in JavaScript?
var
: Function-scopedlet
: Block-scopedconst
: Block-scoped and immutable
- What is a callback function?
A function passed to another function as an argument, executed after the other function completes. - What are closures in JavaScript?
A closure gives access to an outer function’s scope from an inner function. - What are arrow functions?
A shorter syntax for writing functions:const func = () => { /* code */ };
- How is hoisting done in JavaScript?
Variables and function declarations are moved to the top of their scope during the execution phase. - Difference between == and ===?
==
compares values and performs type conversion if necessary, whereas===
strictly compares values and types. - Difference between let and var?
let
is block-scoped,var
is function-scoped. - What are promises in JavaScript?
Promises represent the eventual completion or failure of an asynchronous operation.
States:pending
,resolved
,rejected
. - How do you handle asynchronous code?
- Callbacks
- Promises
- Async/Await
- What is the event loop?
The event loop allows JavaScript to perform non-blocking operations by offloading operations to the system kernel. - What is an Immediately Invoked Function Expression (IIFE)?
A function that runs as soon as it’s defined:(function() { /* code */ })();
- How do you debug JavaScript?
console.log()
for logging- Breakpoints in browser’s developer tools
- Using the
debugger
keyword
- What is the difference between function declarations and function expressions?
- Function Declaration: Declares a named function
- Function Expression: Can be anonymous and is defined inside an expression
- What are JavaScript cookies?
Cookies are small data stored on a user’s browser to track and remember information between sessions. - How do you create and delete a cookie in JavaScript?
- Create:
document.cookie = "username=John; expires=Thu, 18 Dec 2024 12:00:00 UTC"
- Delete:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC"
- What are JavaScript frameworks?
- React.js: For building UI components
- Angular.js: Complete frontend framework
- Node.js: Server-side framework
- What is the difference between undefined and null?
undefined
: A variable has been declared but not yet assigned a value.null
: A value that explicitly represents no value.
- What is the DOM?
The Document Object Model (DOM) represents a web page and allows scripts to access and manipulate its content. - How do you select HTML elements in JavaScript?
getElementById()
getElementsByClassName()
querySelector()
getElementsByTagName()
- What are closures in JavaScript?
A closure is the combination of a function and its lexical environment. - What is the ‘use strict’ directive?
Enables strict mode in JavaScript, which catches common coding mistakes and prevents the use of some unsafe actions. - What is the difference between Call and Apply?
call()
: Invokes a function with arguments passed individually.apply()
: Invokes a function with arguments passed as an array.
- How do you remove duplicates from an array in JavaScript?
UsingSet
:const uniqueArray = [...new Set(array)];
- What is the difference between for, forEach, and map?
for
: General-purpose loopforEach
: Executes a function for each array elementmap
: Creates a new array by applying a function to each element
- How do you empty an array in JavaScript?
arr.length = 0;
arr = [];
arr.splice(0, arr.length);
- What is event bubbling?
Event bubbling is the process where an event triggers on the innermost element first and then propagates to outer elements. - What is event capturing?
Event capturing is the opposite of event bubbling, where the event is captured from the outermost element and propagated to the innermost element. - What is the difference between const and let?
const
: Variable values cannot be reassignedlet
: Values can be reassigned, but they are block-scoped.
- What is currying in JavaScript?
Currying is the process of transforming a function with multiple arguments into a series of functions, each taking a single argument. - What is function composition?
Function composition is combining multiple functions such that the output of one function becomes the input of the next. - How do you create a class in JavaScript?
class Person { constructor(name) { this.name = name; } }
- What is prototypal inheritance?
Objects in JavaScript can inherit properties and methods from other objects via the prototype chain. - What is the difference between synchronous and asynchronous code?
- Synchronous: Code runs sequentially, blocking subsequent code.
- Asynchronous: Code runs concurrently, not blocking the rest of the code.
- What is the difference between fetch() and XMLHttpRequest()?
- fetch(): Modern way to make HTTP requests, returns promises.
- XMLHttpRequest(): Old method, requires callback functions.
- What are generators in JavaScript?
Generators are functions that can be paused and resumed, producing a series of values on demand using theyield
keyword. - What is a WeakSet in JavaScript?
A WeakSet holds objects weakly, meaning they can be garbage-collected if not referenced elsewhere. - What is object destructuring?
Object destructuring allows you to extract values from objects easily:const { name, age } = person;
- What is currying in JavaScript?
Currying transforms a function with multiple arguments into a sequence of functions, each taking one argument. - What is the temporal dead zone in JavaScript?
The period between entering the scope and declaring a variable withlet
orconst
, during which the variable cannot be accessed. - What are JavaScript design patterns?
- Creational: Singleton, Factory
- Structural: Decorator, Adapter
- Behavioral: Observer, Mediator
- What is lexical scoping?
Lexical scoping means that a function’s scope is determined by where it is defined in the source code. - What is a three-dimensional array?
An array that has arrays as elements, and those arrays contain other arrays:[[[]]]
. - What are pop-up boxes in JavaScript?
alert()
confirm()
prompt()
- What is memoization?
Memoization is caching the result of function calls for specific inputs to improve performance. - What are higher-order functions?
Functions that take other functions as arguments or return functions as output. - What is the Browser Object Model (BOM)?
BOM allows interaction with the browser, like manipulating the browser window or history. - Difference between localStorage and sessionStorage?
- localStorage: Persists even after the browser is closed.
- sessionStorage: Data is lost when the session ends.
- What are generator functions?
Functions that return a generator object and can be paused and resumed:function* gen() { yield 1; yield 2; }
- What is a WeakMap?
AWeakMap
holds objects as keys, and these keys can be garbage collected. - What is the difference between document and window objects?
- window: Global object representing the browser window
- document: Object representing the HTML content of the page
- What is object destructuring?
Extract values from objects easily:const { name, age } = person;
- What is an arrow function?
A shorthand way of writing functions:const func = () => console.log('Hello');
- Difference between undefined and undeclared variables?
- Undefined: Variable declared but not assigned a value
- Undeclared: Variable that hasn’t been declared in the code
- What is a rest parameter?
Allows a function to accept an indefinite number of arguments as an array:function sum(...args) {}
- What is a spread operator?
Allows an iterable like an array to be expanded:const arr = [...otherArray];
- What is a Symbol in JavaScript?
A unique and immutable data type used as an identifier for object properties. - What are classes in JavaScript?
ES6 feature for creating objects and handling inheritance:class Person { constructor(name) { this.name = name; } }
- Difference between == and === operators?
==
: Compares values, performs type conversion===
: Strictly compares values and types
- What is NaN?
“Not-a-Number” is a special value representing invalid number operations:typeof NaN // "number"
- What are modules in JavaScript?
A way to organize code by splitting it into separate files:
import { module } from 'module.js'
export const module = 'someValue';
- What is the difference between null and undefined?
null
: Represents intentional absence of valueundefined
: Represents unassigned variables
- What is implicit type coercion?
Automatic conversion of one data type to another:1 + '2' // "12"
- What is the difference between call and apply methods?
call
: Accepts arguments separatelyapply
: Accepts arguments as an array
- What are default parameters in JavaScript?
Allow functions to have default values for parameters:function greet(name = 'Guest') {}
- What is recursion in JavaScript?
A function that calls itself:function factorial(n) { return n ? n * factorial(n - 1) : 1; }
- What is function currying?
Transforming a function with multiple arguments into nested functions:function add(a) { return function(b) { return a + b; }; }
- What is prototypal inheritance?
Objects inherit properties and methods from a prototype:Object.create(parentObject)
- What is event delegation?
Attaching an event listener to a parent element that listens for events on its child elements. - What is the purpose of the async/await syntax?
Simplifies working with promises by making asynchronous code look synchronous. - What is object.freeze()?
Freezes an object, preventing new properties from being added or modified. - How to clone an object in JavaScript?
- Shallow copy:
Object.assign({}, obj)
- Deep copy:
JSON.parse(JSON.stringify(obj))
- What is JavaScript’s strict mode?
Enables stricter parsing and error handling in JavaScript by adding'use strict';
.