Ulloor News

ULLOOR
NEWS

Top 100 javascript Interview questions with answers

Share the Valuable Post

1. What is JavaScript?
JavaScript is a high-level, interpreted programming language used to make web pages interactive. It runs in the browser and also on servers using Node.js.

2. Difference between JavaScript and Java?

  • Java: Object-oriented, compiled, strongly typed.
  • JavaScript: Lightweight, interpreted, loosely typed, primarily for web scripting.

3. Is JavaScript single-threaded or multi-threaded?
JavaScript is single-threaded but can handle asynchronous tasks using the event loop.

4. What are variables in JavaScript?
Variables store data values. Declared using var, let, or const.

5. Difference between var, let, and const?

  • var: Function-scoped, hoisted, can be redeclared.
  • let: Block-scoped, not hoisted the same way, can be reassigned.
  • const: Block-scoped, cannot be reassigned.

6. What are data types in JavaScript?

  • Primitive: string, number, boolean, null, undefined, symbol, bigint.
  • Non-primitive: objects, arrays, functions.

7. What is type coercion?
JavaScript automatically converts one data type to another during operations.
Example: “5” + 1 → “51”.

8. Difference between == and ===?

  • ==: Compares values after type coercion.
  • ===: Strict equality (checks type + value).

9. What is NaN?
NaN means “Not a Number”. Example: parseInt(“abc”).

10. How to check if a value is NaN?
Use isNaN(value) or Number.isNaN(value).

11. What are template literals?
Strings wrapped in backticks (`) that support interpolation:

let name = “John”;

console.log(`Hello, ${name}`);

12. What is hoisting in JavaScript?
Variables and functions are moved to the top of their scope before execution.
Example:

console.log(x); // undefined

var x = 5;

13. What are arrow functions?
A shorter syntax for functions:

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

14. Difference between function declaration and function expression?

  • Declaration: Hoisted.
  • Expression: Not hoisted.

15. What are default parameters?
Function parameters with default values if no argument is passed:

function greet(name=”Guest”){ return `Hello, ${name}` }

16. What is the difference between null and undefined?

  • null: Intentional empty value.
  • undefined: Variable declared but not assigned.

17. What is an object in JavaScript?
A collection of key-value pairs.

18. How do you create an object?

let obj = { name: “John”, age: 30 };

19. What are arrays in JavaScript?
Arrays store ordered collections of items:

let arr = [1,2,3];

20. Difference between for…in and for…of loops?

  • for…in: Iterates over object keys.
  • for…of: Iterates over values of iterable objects (arrays, strings).

21. What is the spread operator?
Expands elements of an array/object:

let arr = [1,2,3];

let newArr = […arr, 4];

22. What is the rest operator?
Collects arguments into an array:

function sum(…nums){ return nums.reduce((a,b)=>a+b); }

23. What are higher-order functions?
Functions that take other functions as arguments or return them.
Example: map, filter, reduce.

24. What is callback in JavaScript?
A function passed as an argument to another function, executed later.

25. What is an event listener?
A method that waits for an event to occur:

element.addEventListener(“click”, () => console.log(“Clicked”));

26. What is the DOM?
Document Object Model — a tree structure representing HTML elements.

27. Difference between innerHTML and innerText?

  • innerHTML: Returns HTML content.
  • innerText: Returns visible text only.

28. What is localStorage and sessionStorage?

  • localStorage: Stores data with no expiration.
  • sessionStorage: Stores data for one session.

29. Difference between synchronous and asynchronous?

  • Synchronous: Executes line by line.
  • Asynchronous: Tasks don’t block execution (e.g., promises, async/await).

30. What is JSON in JavaScript?
JavaScript Object Notation, used for data exchange.

JSON.stringify(obj); 

JSON.parse(jsonStr);

31. What are closures?
A closure is when a function remembers variables from its outer scope even after the outer function is finished.

function outer(){

  let x=10;

  return function inner(){ return x; }

}

32. Why are closures useful?
They help in data encapsulation and maintaining private variables.

33. What is the event loop?
It handles async operations by continuously checking the call stack and callback queue.

34. What are promises?
Promises represent the eventual result of an async operation:

let p = new Promise((resolve,reject)=>{ resolve(“Done”); });

35. Difference between promise and callback?
Promises are easier to chain and handle errors, reducing “callback hell”.

36. What is async/await?
Syntax sugar over promises for cleaner async code:

async function fetchData(){

  let data = await fetch(“url”);

}

37. What is the difference between map, filter, and reduce?

  • map: Transforms array items.
  • filter: Returns items that match condition.
  • reduce: Accumulates values into a single output.

38. What is debouncing?
Limits function execution until after a delay:

function debounce(fn, delay){

  let timer;

  return function(…args){

    clearTimeout(timer);

    timer = setTimeout(()=>fn(…args), delay);

  }

}

39. What is throttling?
Limits function execution to once in a given time interval.

40. Difference between shallow copy and deep copy?

  • Shallow: Copies references, not nested values.
  • Deep: Copies all values recursively.

41. How do you deep clone an object?

let clone = JSON.parse(JSON.stringify(obj));

42. What is prototypal inheritance?
Objects inherit properties/methods from other objects via prototypes.

43. What is the difference between __proto__ and prototype?

  • __proto__: Actual object prototype.
  • prototype: Property of constructor functions used for inheritance.

44. What is the difference between ES5 and ES6?
ES6 introduced let/const, arrow functions, classes, template literals, promises, modules, etc.

45. What are modules in JavaScript?
Reusable code files. Imported/exported using import and export.

46. What is a pure function?
A function that has no side effects and always returns the same output for the same input.

47. What is immutability?
Data that cannot be changed once created.

48. What is the difference between call, apply, and bind?

  • call: Calls function with arguments listed individually.
  • apply: Calls function with arguments as array.
  • bind: Returns a new function with this bound.

49. What is currying?
Breaking down a function with multiple arguments into a series of functions:

function add(a){ return (b)=>a+b; }

50. What is the difference between slice and splice?

  • slice(start,end): Returns a shallow copy.
  • splice(start,count): Modifies array by removing/replacing.

51. What is the difference between setTimeout and setInterval?

  • setTimeout: Runs once after delay.
  • setInterval: Runs repeatedly after interval.

52. What are generators in JavaScript?
Functions that can pause/resume execution using yield.

53. Difference between forEach and map?

  • forEach: Iterates, returns undefined.
  • map: Returns new array.

54. What is a WeakMap and WeakSet?
Collections that hold weak references to objects (not preventing garbage collection).

55. What is a Symbol in JavaScript?
A unique, immutable primitive used as object keys.

56. What is the difference between shallow equality and deep equality?

  • Shallow: Compares references.
  • Deep: Compares actual content recursively.

57. How does garbage collection work in JavaScript?
JS uses reference counting and mark-and-sweep algorithms to free unused memory.

58. What is a polyfill?
Code that implements modern features in older browsers.

59. What is the difference between synchronous and asynchronous iteration?

  • Sync: Iterates immediately.
  • Async: Uses for await…of for promises.

60. What is the difference between typeof null and typeof undefined?

  • typeof null: “object” (historical bug).
  • typeof undefined: “undefined”.

61. What are default exports and named exports?

  • Default: export default function(){}
  • Named: export function test(){}

62. What is memoization?
Caching function results to avoid recomputation.

63. What are tagged template literals?
Functions that modify template literals:

function tag(strings,…values){ return strings[0]+values[0]; }

64. What is the difference between GET and POST in AJAX calls?

  • GET: Retrieves data.
  • POST: Sends data.

65. What is the difference between null == undefined and null === undefined?

  • null == undefined: true
  • null === undefined: false

66. What are async iterators?
They allow asynchronous iteration using for await…of.

67. What is event delegation?
Attaching one event listener to a parent element to handle events of child elements.

68. What is strict mode in JavaScript?
A mode (“use strict”) that enforces stricter parsing, disallows undeclared variables.

69. What is function composition?
Combining multiple functions into one:

const compose = (f,g) => x => f(g(x));

70. What are service workers?
Scripts that run in background, enabling caching, offline mode, push notifications.

71. What is the difference between deep freeze and shallow freeze?

  • Shallow freeze: Freezes only top-level.
  • Deep freeze: Freezes nested objects too.

72. What is tail call optimization?
Optimization where recursive calls don’t add new stack frames.

73. What is dynamic import?
Importing modules at runtime:

import(“./module.js”).then(…)

74. Difference between microtasks and macrotasks?

  • Microtasks: Promise callbacks, process.nextTick.
  • Macrotasks: setTimeout, setInterval.

75. What is the difference between Object.freeze and Object.seal?

  • freeze: Prevents adding/removing/changing properties.
  • seal: Prevents adding/removing, but allows modification.

76. What is the difference between static and instance methods?

  • Static: Belongs to class, called without object.
  • Instance: Called on object.

77. What is a proxy in JavaScript?
An object that intercepts operations like get, set.

78. What is reflection in JavaScript?
Meta-programming feature via Reflect API for intercepting operations.

79. What is the difference between async/await and generators?
Both manage async flow, but async/await is simpler syntax built on promises.

80. What is the difference between Object.assign and spread operator?
Both copy properties, but spread cannot copy property descriptors.

81. What are WeakRefs?
Weak references to objects, not preventing garbage collection.

82. What is event bubbling and capturing?

  • Bubbling: Event moves from child to parent.
  • Capturing: Event moves from parent to child.

83. What are web workers?
Background threads in browsers for running scripts without blocking UI.

84. What is shadow DOM?
Encapsulation of styles and DOM for web components.

85. What are decorators in JavaScript?
Functions that modify classes/methods.

86. What is the difference between synchronous generator and async generator?

  • Sync: Uses yield.
  • Async: Uses async function* and for await.

87. What are ES6 classes?
Syntactic sugar over prototypes.

88. What are mixins in JavaScript?
A way to add properties/methods to a class from multiple sources.

89. What is optional chaining?
Safe property access:

let name = user?.address?.street;

90. What is nullish coalescing?
?? returns right-hand value only if left-hand is null or undefined.

91. What are TypedArrays?
Arrays that store binary data (e.g., Int8Array).

92. What is BigInt?
A numeric type for arbitrarily large integers.

93. What is Intl API in JavaScript?
Internationalization API for formatting numbers, dates, etc.

94. What is function hoisting difference between arrow and normal functions?

  • Normal functions hoist.
  • Arrow functions do not.

95. What are promises.all, promises.race, and promises.any?

  • Promise.all: Resolves when all promises resolve.
  • Promise.race: Resolves when first promise settles.
  • Promise.any: Resolves when first promise fulfills.

96. What are pipelines in JavaScript?
Proposed feature: value |> function.

97. What is the difference between frontend and backend JavaScript?

  • Frontend: DOM manipulation, UI events.
  • Backend: Server-side logic, database, APIs.

98. What are observables in JavaScript?
Reactive programming feature (RxJS) for handling async streams.

99. What is the difference between mutable and immutable objects?

  • Mutable: Can be changed after creation.
  • Immutable: Cannot be changed.

100. What are JavaScript design patterns?
Reusable solutions for common problems: Singleton, Factory, Observer, Module, etc.


Share the Valuable Post
Scroll to Top