Top 50 JavaScript Interview Questions & Answers for 2025

javascript interview

JavaScript is a must-know for any frontend or full-stack developer. Here are the top 50 JavaScript interview questions and answers that cover fundamental concepts, advanced topics, and common coding scenarios.


Basics of JavaScript

1. What is JavaScript?
JavaScript is a lightweight, interpreted scripting language used to make web pages interactive. It runs on the client side and allows for dynamic updates to content, user interface behavior, and real-time content changes.

2. How is JavaScript different from Java?
Java is a statically typed, compiled, object-oriented programming language used for server-side or application development, whereas JavaScript is dynamically typed, interpreted, and mainly used for front-end web development.

3. What are the data types in JavaScript?
JavaScript supports the following data types: Primitive types (String, Number, BigInt, Boolean, Undefined, Symbol, Null) and Non-primitive types (Object, Array, Function).

4. What is the difference between == and ===?
== checks for value equality with type coercion, while === checks for both value and type equality, making it more strict and reliable.

5. What is undefined vs null?
undefined is the default value for uninitialized variables. null is an intentional assignment that represents no value or an empty object reference.

6. How do you declare a variable in JavaScript?
You can declare variables using var (function-scoped), let (block-scoped), and const (block-scoped and read-only).

7. What is hoisting?
Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope before code execution. Only declarations are hoisted, not initializations.

8. What is a closure?
A closure is a function that retains access to its lexical scope, even after the outer function has returned. It allows for data privacy and function encapsulation.

9. What is the difference between var, let, and const?

  • var is function-scoped and allows re-declaration.
  • let is block-scoped and doesn’t allow re-declaration within the same block.
  • const is also block-scoped but requires immediate initialization and doesn’t allow reassignment.

10. What is the typeof operator?
typeof is used to determine the type of a variable. For example, typeof 'hello' returns “string”.


Functions and Scope

11. What are arrow functions?
Arrow functions provide a shorter syntax for writing functions and do not bind their own this. They are useful in callbacks and methods that don’t require their own context.

12. What is the difference between function declaration and function expression?
Function declarations are hoisted and can be called before they’re defined. Function expressions are not hoisted and must be defined before use.

13. What is a callback function?
A callback is a function passed as an argument to another function, typically used for asynchronous operations like loading data or handling events.

14. What is lexical scope?
Lexical scope means that a variable defined outside a function can be accessible inside it, but not the other way around. It’s based on where functions and blocks are written in the code.

15. What is an IIFE?
An Immediately Invoked Function Expression (IIFE) is a function that runs immediately after it’s defined. It’s commonly used to create private scopes in JavaScript.

16. What is the this keyword?
this refers to the object from which a function is called. In global scope, it refers to the window object; in methods, it refers to the owner object.

17. How does this work in arrow functions?
Arrow functions do not have their own this. Instead, they inherit this from their lexical context (the enclosing function or object).

18. What is the difference between synchronous and asynchronous code?
Synchronous code executes line by line, blocking further execution until the current operation completes. Asynchronous code (e.g., with setTimeout, Promises) runs in the background and doesn’t block the main thread.

19. What are Promises?
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, and rejected.

20. What is async/await?
async and await provide a cleaner way to work with Promises. An async function always returns a Promise, and await pauses execution until the Promise resolves or rejects.


Objects and Arrays

21. How do you create an object in JavaScript?
You can create an object using object literals or constructors. Example:

const person = { name: 'John', age: 30 };

22. How do you loop through an object?
You can use for...in to iterate over properties or Object.keys()/Object.entries() with forEach() or for...of.

23. How do you merge two objects?
You can merge using the spread operator or Object.assign():

const merged = { ...obj1, ...obj2 };

24. How do you create an array in JavaScript?
An array can be created using square brackets:

const fruits = ['apple', 'banana'];

25. How do you add/remove elements from an array?
Use push() and pop() for the end, shift() and unshift() for the beginning, and splice() to add/remove at a specific index.

26. What are higher-order functions?
Functions that take other functions as arguments or return them. Examples include map(), filter(), and reduce().

27. What are common array methods?
map(), filter(), reduce(), forEach(), find(), some(), and every() are commonly used for iteration and transformation.

28. How do you clone an array?
Use the spread operator or Array.from():

const clone = [...original];

29. What is destructuring?
Destructuring allows unpacking values from arrays or properties from objects into distinct variables:

const [a, b] = [1, 2];
const { name } = person;

30. What is the difference between slice() and splice()?

  • slice() returns a shallow copy of a portion of an array without modifying the original.
  • splice() modifies the original array by adding/removing elements.

DOM & Events

31. How do you select an element in the DOM?
You can select DOM elements using methods like getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector(), and querySelectorAll(). querySelector is widely used for selecting elements with CSS selectors.

32. How do you add an event listener?
Use the addEventListener() method to attach an event to an element. For example:

document.getElementById('btn').addEventListener('click', function() {
  alert('Button clicked');
});

33. What is event bubbling and capturing?
Event bubbling is the process where an event starts from the innermost target element and propagates up to parent elements. Capturing is the opposite direction. You can control it with the third parameter of addEventListener.

34. How do you stop event propagation?
Call event.stopPropagation() within the event handler to stop the event from reaching parent elements.

35. How do you prevent default behavior?
Use event.preventDefault() to stop default actions like form submission or link navigation.

36. How do you create a new DOM element?
Use document.createElement() to create an element and then use methods like appendChild() or append() to insert it:

const div = document.createElement('div');
div.textContent = 'Hello';
document.body.appendChild(div);

37. How do you change an element’s content?
You can change the content of an element using innerHTML for HTML or textContent for plain text. Example:

div.innerHTML = '<strong>Hello</strong>';
div.textContent = 'Just text';

38. What is the difference between innerHTML and textContent?
innerHTML parses and inserts HTML, which can expose you to XSS attacks if not handled properly. textContent just inserts plain text.

39. How do you set styles with JavaScript?
Use the .style property of an element:

element.style.backgroundColor = 'blue';
element.style.fontSize = '18px';

40. What are data attributes and how do you access them?
Data attributes are custom attributes in HTML prefixed with data-. You can access them with the .dataset property:

<div data-id="123"></div>
div.dataset.id; // returns "123"

Advanced JavaScript

41. What is event delegation?
Event delegation means attaching a single event listener to a parent element to handle events on its child elements. It utilizes event bubbling and improves performance.

42. What is a module in JavaScript?
Modules are reusable pieces of code that export functionality and import it elsewhere. In ES6+, we use export and import to create modules. Modules help organize large codebases.

43. What is the difference between == and Object.is()?
Both compare values, but Object.is() handles edge cases more precisely, such as NaN and signed zeros:

Object.is(NaN, NaN); // true
NaN === NaN; // false

44. What is the difference between call(), apply(), and bind()?
These methods allow you to set the this context of a function:

  • call(): calls a function with given arguments individually.
  • apply(): same as call() but with arguments as an array.
  • bind(): returns a new function with a bound this value.

45. What is a prototype?
Every JavaScript object has a prototype, which is a blueprint from which it inherits properties and methods. Prototypes form the basis for inheritance in JavaScript.

46. What is the difference between prototypal and classical inheritance?
Classical inheritance (as in Java or C++) is class-based. JavaScript uses prototypal inheritance, where objects inherit directly from other objects.

47. What are setTimeout() and setInterval()?

  • setTimeout(fn, delay): runs a function once after a delay.
  • setInterval(fn, delay): runs a function repeatedly at intervals. Both are asynchronous and rely on the event loop.

48. What is the event loop?
The event loop is a mechanism that handles asynchronous operations by placing them in a queue and executing them when the call stack is empty.

49. What is a memory leak in JavaScript?
A memory leak happens when objects are no longer needed but are still referenced, preventing garbage collection and consuming memory.

50. How do you debug JavaScript code?
You can use:

  • console.log() for output
  • Browser developer tools
  • Breakpoints in the debugger
  • debugger keyword in code to pause execution

#JavaScript #JSInterviewQuestions #FrontendDeveloper #FullStackDeveloper #WebDevelopment #LearnJS #CodeNewbie #TechInterview #JSTips #CodingInterview

Leave a comment

Trending