JavaScript Questions You Should Know
1. Explain what is JavaScript?
JavaScript is a high-level, interpreted, dynamically typed programming language primarily used to add interactivity, complex features, and dynamic behavior to web pages.
2. Is JavaScript single threaded or multithreaded? Explain in detail.
JavaScript is inherently single-threaded, meaning it executes one command at a time in a single Call Stack. However, it achieves concurrency and non-blocking behavior through the Event Loop and Web APIs (like setTimeout, fetch, and DOM events), which offload heavy tasks to the browser and push callbacks back to the stack when ready.
3. How can I add JavaScript in my HTML code? Give me 2 possible ways.
- Internal: Wrapping JavaScript code inside a
<script>tag directly in the HTML file. - External: Linking an external
.jsfile using<script src="app.js"></script>.
4. Can I add a script tag in the head element?
Yes, you can add a <script> tag inside the <head> element. However, doing so without defer or async attributes will halt the HTML parsing until the script is fully downloaded and executed.
5. Does adding script tag in head element cause any problem?
Yes, it causes render-blocking. Since HTML parsing pauses to fetch and execute the script, the user will see a blank screen until the script finishes loading, drastically degrading performance.
6. What are async and defer attributes?
async: Downloads the script asynchronously alongside HTML parsing, and executes it the moment it finishes downloading (pausing HTML parsing momentarily). Order of execution is not guaranteed.defer: Downloads the script asynchronously but guarantees execution only after the entire HTML document is fully parsed. Maintains the order of execution.
7. Explain data types in JavaScript.
JavaScript has two categories of data types:
- Primitives:
String,Number,BigInt,Boolean,Undefined,Null, andSymbol. These are immutable and stored by value. - Non-Primitives (Objects):
Object,Array,Function,Date. These are mutable and stored by reference.
8. What is hoisting? Give examples.
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope before code execution.
console.log(x); // undefined (declaration hoisted, not initialization)
var x = 5;
hello(); // works! (function declarations are fully hoisted)
function hello() { console.log("Hi"); }
Note: let and const are hoisted but remain in a "Temporal Dead Zone" until initialization.
9. What is closure? Give examples.
A closure is a function that "remembers" the variables and data from its outer lexical scope, even after that outer function has returned.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
}
}
const counter = outer();
counter(); // 1
counter(); // 2
10. What is stale closure? Give examples.
A stale closure occurs when a closure captures an outdated variable reference and fails to see its updated state, often happening in React hooks.
// Example in React useEffect:
useEffect(() => {
const interval = setInterval(() => {
setCount(count + 1); // count is trapped at 0! (Stale Closure)
}, 1000);
}, []); // Empty dependency array traps the initial count
11. Explain currying, its use case and its benefits.
Currying transforms a function with multiple arguments into a sequence of nested functions that each take a single argument. f(a, b, c) becomes f(a)(b)(c).
Benefits: It helps in function composition, avoids passing the same variables repeatedly, and creates highly reusable, specialized functions.
12. What is an IIFE?
IIFE stands for Immediately Invoked Function Expression. It is a JavaScript function that runs as soon as it is defined, preventing its internal variables from polluting the global scope.
13. Give 4 ways to create an IIFE.
- Standard:
(function() { /* code */ })(); - Arrow:
(() => { /* code */ })(); - Unary Plus:
+function() { /* code */ }(); - Logical NOT:
!function() { /* code */ }();
14. What are operators in JS?
Operators are symbols used to perform operations on operands. Types include:
- Arithmetic:
+,-,*,/,% - Assignment:
=,+=,-= - Comparison:
==,===,!=,>,< - Logical:
&&,||,! - Ternary:
condition ? true : false
15. How can I check data type of variables in JS?
You can use the typeof operator for primitives and Array.isArray() or instanceof for non-primitives.
typeof "Hello" // "string"
typeof 42 // "number"
Array.isArray([1, 2]) // true
16. Explain Abstract Equality in JavaScript (==).
Abstract equality (==) compares two values for equality after performing type coercion if they are of different types. For example, 5 == "5" evaluates to true because the string is coerced into a number before comparison.
17. How == is different from ===?
==(Loose Equality) performs type coercion.0 == falseistrue.===(Strict Equality) checks BOTH value and type without coercion.0 === falseisfalse. It is best practice to always use===.
18. Explain Execution Context.
The Execution Context is the environment in which JavaScript code evaluates and executes. It consists of the Memory Component (where variables and functions are stored as key-value pairs) and the Code Component (the thread of execution where code runs line by line).
19. What is Lexical Scope?
Lexical scope means that a variable's scope is defined by its physical placement within the source code. Nested functions have access to variables declared in their outer scope, but outer functions cannot access variables defined inside inner functions.
20. Explain this keyword.
The this keyword refers to the object that is executing the current function.
- In an object method,
thisrefers to the object. - In a standalone function,
thisrefers to the global object (windowin browsers), orundefinedin strict mode. - In an arrow function,
thisinherits from its lexical parent.
21. What is call, bind, and apply?
They explicitly set the this context for a function.
call(): Invokes the function immediately, passing arguments individually (func.call(thisArg, arg1, arg2)).apply(): Invokes the function immediately, passing arguments as an array (func.apply(thisArg, [arg1, arg2])).bind(): Returns a new function withthisbound, but does not invoke it immediately.
22. Explain what is the new keyword.
The new keyword is used to create an instance of a user-defined object type or constructor function. It does four things:
- Creates a brand new empty object.
- Links that object to the constructor's prototype.
- Binds the
thiskeyword to the new object. - Returns the object automatically.
23. What are prototypes in JS?
Prototypes are the mechanism by which JavaScript objects inherit features from one another. Almost every object in JavaScript has a built-in property, called its prototype. The prototype is itself an object, creating a "prototype chain" until it reaches null.
24. Explain difference between __proto__, prototype, [[Prototype]].
[[Prototype]]: The hidden, internal specification property that points to an object's prototype.__proto__: The historical, exposed getter/setter to access an object's[[Prototype]](deprecated in favor ofObject.getPrototypeOf()).prototype: A property specifically on Constructor Functions used to build__proto__for its instances.
25. What is prototypical inheritance? How is it different from classical inheritance?
Prototypal inheritance means objects inherit directly from other objects via the prototype chain. Classical inheritance (Java/C++) means classes inherit from other classes, and objects are instantiated from those blueprints. JavaScript uses prototypes under the hood, even when using the class syntax.
26. What is the difference between var, let, and const?
var: Function-scoped, can be redeclared, hoisted and initialized toundefined.let: Block-scoped, can be reassigned but not redeclared, hoisted but uninitialized (TDZ).const: Block-scoped, cannot be reassigned or redeclared, must be initialized upon declaration.
27. What are Symbols in JS?
Symbol is a primitive data type that generates a completely unique, anonymous identifier. They are primarily used to add unique property keys to objects that won't conflict with other keys or show up in normal iterations (for...in).
28. What is the spread and rest concept in JS?
- Spread (
...): Expands an array or object into its individual elements. Useful for copying or merging arrays ([...arr1, ...arr2]). - Rest (
...): Condenses multiple elements into a single array. Used in function parameters to handle an infinite number of arguments (function sum(...numbers)).
29. Explain destructuring.
Destructuring assignment is a syntax that makes it possible to unpack values from arrays, or properties from objects, directly into distinct variables in a single line.
const user = { name: "John", age: 25 };
const { name, age } = user;
30. Explain difference between || and ??.
||(Logical OR): Returns the right side if the left side is falsy (0,"",false,null,undefined,NaN).??(Nullish Coalescing): Returns the right side ONLY if the left side is strictlynullorundefined. It preserves valid falsy values like0or"".
31. What is optional chaining?
Optional chaining (?.) allows you to safely read the value of a property located deep within a chain of connected objects without having to check if each reference in the chain is valid. If a reference is nullish, it short-circuits and returns undefined.
const zip = user?.address?.zipCode;
32. What is functional programming?
Functional programming is a programming paradigm where applications are built primarily using pure functions, avoiding shared state, mutable data, and side effects. It treats computation as the evaluation of mathematical functions.
33. What is the difference between reduce and reduceRight?
Both apply a function against an accumulator and each value of the array to reduce it to a single value.
reduce(): Processes the array from left to right (index 0 to n).reduceRight(): Processes the array from right to left (index n down to 0).
34. What are callbacks?
A callback is a function passed as an argument into another function, which is then invoked inside the outer function to complete some kind of routine or action. Callbacks are heavily used for asynchronous operations.
35. Explain inversion of control.
Inversion of Control (IoC) in the context of JS callbacks happens when you pass your callback function into an external library or asynchronous function. You lose control over when or how many times your callback is executed, trusting the external code to handle it correctly. This trust issue is why Promises were introduced.
36. What are promises?
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. It fixes the callback hell/inversion of control issue by allowing you to attach .then() handlers instead of passing callbacks directly.
37. What are the different states of promises?
- Pending: The initial state, neither fulfilled nor rejected.
- Fulfilled (Resolved): The operation completed successfully.
- Rejected: The operation failed. Note: Once a promise is fulfilled or rejected, it is considered "settled" and cannot change state.
38. When does the finally block get called under promises?
The .finally() block gets executed when the promise settles, regardless of whether it was resolved or rejected. It is perfect for cleanup operations, like hiding a loading spinner.
39. How can I handle errors using try...catch in JS?
Wrap potentially failing, synchronous, or await-ed code inside a try block. If an error is thrown, the execution jumps to the catch block where you can handle the error without crashing the app.
try {
const data = await fetchApi();
} catch (error) {
console.error("Failed:", error);
}
40. What is tagged template literal?
A tagged template literal is an advanced feature where a function is called directly on a template string. The function parses the literal strings and the interpolated values, commonly used in libraries like styled-components.
styled.div`
color: red;
`
41. How does this work inside the arrow function?
Arrow functions do not have their own this binding. Instead, they lexically inherit this from the parent scope at the time they are defined. This makes them perfect for callbacks inside class methods where you don't want this to point to the global object.
42. What is the difference between an arrow and normal function? Explain 7 differences.
- Syntax: Arrow functions are shorter
() => {}. thiscontext: Normal functions have their ownthis; Arrow functions inheritthislexically.- Arguments object: Arrow functions do not have access to the
argumentskeyword. - Constructor: Normal functions can be called with
new; Arrow functions cannot. - Hoisting: Normal
functiondeclarations are hoisted; Arrow functions (assigned to vars/lets) are not. - Super: Arrow functions do not have their own
superbinding. - Implicit Return: Arrow functions allow omitting the
returnkeyword for single-line expressions.
43. Explain Sets. How are they different from arrays?
A Set is a collection of completely unique values of any type. Unlike arrays, a Set does not allow duplicate entries and does not have an index-based access mechanism. Sets are highly optimized for checking if a value exists (set.has(val)).
44. What is the arguments keyword present in functions in JavaScript?
It is an array-like object accessible strictly inside normal non-arrow functions. It contains the values of all arguments passed to the function, regardless of whether they were explicitly declared in the function signature. Modern JS prefers the Rest parameter (...args) instead.
45. What is "use strict" and what it does?
"use strict"; is a literal string placed at the top of a script or function to enforce Strict Mode. It makes JavaScript throw errors for silent failures (like assigning variables without declaring them), prohibits deleting plain variables, and makes the this keyword undefined instead of window in global functions.
46. How does the for...of loop differ from the for...in loop?
for...of: Iterates over the values of iterable objects (like Arrays, Strings, Sets, Maps).for...in: Iterates over the enumerable keys (property names/indices) of an object or array. Usually reserved for Objects.
47. How does the async/await syntax simplify asynchronous code in JavaScript?
It acts as syntactic sugar over Promises, allowing you to write asynchronous, non-blocking code in a synchronous, top-to-bottom style. It eliminates .then() chains and prevents deeply nested callback structures.
48. Explain the difference between map and filter.
map(): Transforms every element in an array and returns a new array of the exact same length.filter(): Tests every element against a condition and returns a new array containing only the elements that passed the test (often resulting in a shorter array).
49. What are Map and WeakMap in JavaScript?
Map: A collection of key-value pairs where keys can be any data type (even objects). It remembers the original insertion order.WeakMap: Similar to a Map, but keys must be objects. References to keys are "weak", meaning if the key object has no other references in memory, it gets garbage-collected to prevent memory leaks.
50. What are WeakRef in JavaScript?
WeakRef allows you to hold a weak reference to an object, meaning it won't prevent that object from being permanently deleted by the garbage collector. It's used for highly advanced memory management, like keeping a cache that frees up memory when the system needs it.
51. What is difference between setTimeout and requestAnimationFrame?
setTimeout: Executes a callback after a specified delay in milliseconds, regardless of screen refresh rates. Often inaccurate due to event loop blocking.requestAnimationFrame: Asks the browser to execute a callback right before the next repaint, perfectly syncing with the monitor's refresh rate (typically 60fps) for extremely smooth animations.