Java Script
Java Script
Java typically uses threads and locking. JavaScript uses a single-threaded event loop with
asynchronous callbacks, promises, and async/await.
number — numeric values (floating point and integer; NaN, Infinity are number)
object — arrays, functions, classes, plain objects, dates, maps, sets, etc
Hoisting is a byproduct of how the V8 compilation process reads your file. Before executing a single
line of code, the engine scans the scope during the Creation Phase to register variable and function
setups.
Hoisting is a behavior in JavaScript where the engine allocates memory for variable and function
declarations during the Creation Phase of an execution context, before any code is actually executed.
It is the engine scanning your code for declarations before running it line-by-line. Function
declarations are fully loaded into memory, var variables are registered as undefined, and let/const
variables are registered but kept completely uninitialized in a restricted state called the Temporal
Dead Zone (TDZ).
function createIncrementer() {
var value = 5;
return function() {
value += 5;
};
}
myFunc();
myFunc();
Current value: 10
Current value: 15
undefined means a variable has been declared but not assigned; it’s often produced by the runtime
NaN stands for “Not-A-Number”. It’s a special numeric value that indicates an invalid number result
(e.g., parseInt("abc"), 0/0, [Link](-1)
[Link](NaN); // true
[Link]("foo"); // false
isNaN("foo"); // true (because "foo" coerces to NaN)
NaN !== NaN; // true
0 == '0' // true
0 === '0' // false
null == undefined // true
null === undefined // false
• var
• let
• const
Block-scoped.
For objects/arrays, the binding is constant (reference), but object properties or array items can be
mutated
Template literals (ES6) are string literals enclosed by backticks (`) that can contain placeholders,
multi-line text, and embedded expressions.
Example:
const a = 2, b = 3;
`${a} + ${b} = ${a + b}` // "2 + 3 = 5"
• [Link](1, 2, 3)
An object is an unordered collection of key-value pairs (properties). Keys are strings or symbols.
Values can be primitives or other objects (including functions). Objects are reference types and form
the building block for custom data structures. Objects implement prototypes which allow inheritance
(prototype chain).
Coercion is automatic or implicit conversion from one type to another. JS often coerces values to
numbers, strings, or booleans depending on context
• if ('') → false
• Number('42') → 42
• String(123) → '123'
• Boolean(0) → false
• parseInt('12', 10) → 12
The Document Object Model (DOM) is a tree-like representation of HTML/XML documents exposed
by the browser. JavaScript interacts with DOM to read/update structure, attributes, styles, and
respond to events. DOM nodes include elements, text nodes, comments, etc.
APIs: [Link], [Link], [Link],
refers to browser-provided objects outside the DOM that let JS interact with the browser
environment: window, navigator, location, history, screen, alert, setTimeout, etc.
Synchronous code executes sequentially — each operation blocks the next until it completes.
Example:
const a = computeA();
const b = computeB(a); // computeB runs only after computeA finishes
Asynchronous code schedules operations to complete later (non-blocking), letting other code run in
the meantime. In JS this is done via callbacks, promises, async/await, and events. Examples: network
requests (fetch), timers (setTimeout), reading files in [Link].
The event loop is the runtime mechanism that allows JavaScript’s single-threaded execution to
handle asynchronous operations. It repeatedly:
1. Takes the next task from the task queue (macrotasks) — e.g., setTimeout callback, I/O
callbacks.
Microtask queue — [Link], queueMicrotask callbacks; processed after current stack frame
but before next macrotask.
The call stack is a LIFO (last-in, first-out) stack that keeps track of function calls. When a function is
invoked, it’s pushed onto the stack. When it returns, it’s popped. If the stack grows too deep (deep
recursion), you get a stack overflow.
Heap is the region of memory used for dynamic allocation — objects and closures are stored here
the call stack (where primitive local variables and call frames live), the heap stores objects that
outlive function calls.
In JavaScript functions are objects — they can be assigned to variables, passed as arguments, and
returned from other functions. Declarations are hoisted with their body.
A function declaration (or function statement) defines a named function with the function keyword
and a name. Declarations are hoisted (you can call them before they appear in source).
sayHi();
function sayHi() {
[Link]('Hi');
}
A function expression creates a function and assigns it to a variable. It can be named or anonymous.
Unlike declarations, only the variable binding is hoisted (with var it’s undefined), not the function
body.
Default parameters let you specify default values for parameters when arguments are undefined.
Lexical (static) scope means a function’s accessible variables are determined by where it’s written in
the source code. Inner functions can access variables from outer (enclosing) scopes.
function outer() {
let x = 5;
function inner() {
return x; // captures x lexically
}
}
A closure is a function together with the lexical environment that allows it to access variables from
an outer scope even after that outer function has returned.
function makeCounter() {
let count = 0;
return function() {
return ++count;
};
}
const c = makeCounter();
c(); // 1
Tip: Closures keep data alive; be mindful of memory leaks if they hold large objects.
An IIFE (Immediately Invoked Function Expression) is a function expression that runs immediately
after creation. Historically used to create a private scope before modules.
(function() {
const secret = 42;
[Link]('IIFE ran');
})();
Currying transforms a function with multiple arguments into a sequence of functions each taking a
single argument.
Partial application fixes some arguments of a function and returns a new function expecting the
remaining arguments.
Or using bind:
Distinction: Currying breaks args into unary functions; partial application fixes specific args and
returns a function awaiting the rest.
Recursion is when a function calls itself to solve subproblems. Must have a base case to stop
recursion.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
function declarations are hoisted with their definitions. Function expressions assigned to var are
hoisted as undefined; let/const also hoisted but in TDZ.
A pure function returns the same output for the same inputs and has no side effects (does not
modify external state, no I/O).
An impure function has side effects (mutates external state, depends on external state, performs
I/O) or returns different outputs for same inputs.
let count = 0;
function increment(){ return ++count; } // impure
constructor function (classical JS style) uses new to create objects and assign this. ES6 class is
syntactic sugar.
function Person(name) {
[Link] = name;
}
const p = new Person('Asha');
factory function returns new objects. It’s an alternative to new and constructor functions.
function createUser(name) {
return {
name,
greet() { return `Hi ${name}`; }
};
}
Every function in JS has a prototype property (an object) used when the function is used as a
constructor — instances created by new Fn() inherit from [Link]. Functions themselves (being
objects) also have an internal prototype (__proto__) pointing to [Link].
function Foo(){}
[Link] = () => 'hi';
const f = new Foo();
[Link](); // 'hi'
Shadowing happens when a variable in an inner scope has the same name as a variable in an outer
scope, hiding (shadowing) the outer one.
let x = 1;
function test(){
let x = 2; // shadows outer x
[Link](x); // 2
}
TDZ is the time between entering a block scope and a let/const variable’s declaration where the
variable exists but cannot be accessed — accessing it throws ReferenceError.
{
// [Link](a); // ReferenceError
let a = 1;
}
Callback hell (pyramid of doom) refers to deeply nested callbacks that are hard to read and maintain.
Replaced by Promises, async/await, or flattening techniques.
doA(a => {
doB(b => {
doC(c => {
// nested
});
});
});
An async function returns a Promise. Inside you can use await to pause execution until a Promise
resolves. Errors thrown become rejected Promises.
Example:
• If callback returns undefined for some item, undefined appears in the output array.
• Use for transformations; prefer forEach for side effects and map when you need the
transformed result.
[Link]() returns a new array containing only the elements for which the provided
predicate function returns a truthy value. It does not mutate the original array.
Example:
[Link]() applies a reducer function against an accumulator and each value of the
array (left-to-right) to reduce the array to a single value (can be an object, array, number, etc.).
Signature:
Example (sum):
Use cases:
• If initialValue is omitted, the first element is used as the initial accumulator and iteration
starts from index 1 — be careful with empty arrays (throws).
• find(predicate) returns the first element that satisfies the predicate, or undefined if none
match.
Example:
Choose find when you need a single match; filter for multiple.
[Link]() tests whether at least one element in the array passes the provided
predicate. Returns true or false. Short-circuits on first truthy result.
Example:
Example:
Example:
Notes:
Example:
Use when mapping returns arrays and you want a single flattened array as the result.
Example:
Use cases:
let x = 1, y = 2;
[x, y] = [y, x]; // swap
Example:
Notes:
11. What is optional chaining?Optional chaining (?.) safely accesses nested properties or methods,
returning undefined if a reference is null/undefined instead of throwing.
Example:
Use to avoid lots of && checks for deep property access. Be mindful optional chaining short-circuits
only on null/undefined.
Nullish coalescing operator (??) returns the right-hand operand when the left-hand
is null or undefined, otherwise returns the left-hand. It differs from || which treats many falsy values
as triggers.
Example:
Use when you want to provide defaults only for null/undefined, not for other falsy values.
Shorthand property syntax creates object properties with names equal to variable names.
Example:
const obj = {
sayHi() { return "hi"; } // method shorthand
};
JSON (JavaScript Object Notation) is a lightweight, text-based format to represent structured data
(objects, arrays, primitives). It is language-agnostic and widely used for data interchange.
Example JSON:
Notes:
• Only supports a subset of JS types: objects, arrays, strings, numbers, true, false, null.
Functions and undefined are not representable.
Example:
Options:
Gotcha:
• undefined, functions, and symbols are omitted (or converted to null in arrays).
[Link](text, reviver?) parses a JSON string and returns the corresponding JavaScript value.
Example:
This works for simple data (no functions, Dates, undefined, Maps, Sets, or circular refs), but fails on
those types.
Shallow clone creates a new top-level object whose properties reference the same nested objects as
the original (only the first level is copied).
Examples:
const obj = { a: 1, b: { c: 2 } };
Use shallow clone when nested mutations are not a concern; otherwise use deep cloning.
[Link](target, ...sources) copies enumerable own properties from sources to target (shallow
copy) and returns target.
Example:
const a = { x: 1 };
const b = { y: 2 };
[Link](a, b); // a is now { x:1, y:2 }
Examples:
const a = [1,2];
const b = [...a, 3]; // [1,2,3] (copy then add)
const copy = [...a]; // shallow copy
Object spread ({ ...obj }) shallow-copies enumerable own properties into a new object.
Example:
const o = { a: 1 };
const o2 = { ...o, b: 2 }; // { a:1, b:2 }
[Link](obj) makes an object immutable: you cannot add, remove, or change its existing
properties (shallow freeze). It returns the same object.
Example:
Note:
• Shallow only — nested objects remain mutable. For deep immutability, recurse and freeze
nested objects
• const o = { a: 1 };
[Link](o);
o.b = 2; // ignored / fails
o.a = 3; // allowed
Common ways:
Example:
Common ways:
• [Link]():
Notes:
• Both are shallow merges. Nested objects are referenced, not deep-merged.
• For deep merges use libraries (Lodash _.merge) or custom recursive merge.
[Link]() creates a new array from an array-like or iterable object, optionally mapping each
element through a map function.
Examples:
[Link]("abc"); // ["a","b","c"]
[Link]({ length: 3 }, (_, i) => i); // [0,1,2]
[Link](nodeList); // convert NodeList to Array
[Link]() creates a new array from arguments (unlike new Array(3) which creates an empty array
with length 3).
Examples:
[Link](1,2,3); // [1,2,3]
[Link](3); // [3] (whereas new Array(3) => empty array of length 3)
Examples:
Benefits:
• Cleaner extraction of needed fields, default values, and reduces boilerplate inside function.
Array-like objects look like arrays — they have numeric indexed properties and usually
a length property — but lack array prototype methods (map, forEach, etc.).
Examples: arguments object in non-arrow functions, DOM NodeList, HTMLCollection.
let declares a block-scoped variable. Unlike var, let does not hoist to function scope (it has a
Temporal Dead Zone until declaration) and cannot be redeclared in the same scope. Use let for
variables that need reassignment and should be confined to {} blocks.
if (true) {
let x = 1;
}
[Link](typeof x); // undefined / ReferenceError
A Promise is an object that represents the eventual completion (or failure) of an asynchronous
operation and its resulting value. It has states: pending, fulfilled, or rejected. Promises
provide .then, .catch, and .finally.
Example:
Promise chaining links multiple asynchronous steps by returning a promise inside a .then handler so
the next .then receives the resolved value. This avoids callback hell and creates linear flows.
Example:
fetch(url)
.then(r => [Link]())
.then(data => process(data))
.catch(err => [Link](err));
[Link](iterable) returns a new promise that fulfills when all input promises fulfill (with an array
of results) or rejects immediately if any input rejects. Use for parallel execution where all results are
needed.
Example:
[Link](iterable) returns a promise that settles as soon as the first input promise settles (fulfills
or rejects). Useful for timeout patterns.
Example:
[Link]([fetch(url), timeoutPromise(5000)])
.then(res => ...)
.catch(err => ...);
[Link](iterable) fulfills as soon as any promise fulfills, resolving with that value. It rejects only if
all input promises reject, producing an AggregateError. Useful when you need the first successful
result.
Example:
[Link]([p1, p2])
.then(value => [Link](value))
.catch(err => [Link](err)); // AggregateError if all fail
[Link](iterable) waits for all promises to settle and returns an array describing each
outcome ({status: 'fulfilled', value} or {status: 'rejected', reason}). Useful when you need all results
regardless of failures.
Example:
Destructuring extracts values from arrays or properties from objects into separate variables
succinctly.
Array:
Object:
Definition: Writing code so operations that take time (I/O, timers, network, disk) run without
blocking the main execution thread.
Behavior: Instead of waiting synchronously, you schedule work and provide
callbacks/promises/async functions to run when the operation completes.
Example: fetch(url).then(res => [Link]()) — network happens asynchronously; the main thread
continues.
Pitfall: Forgetting to handle errors (unhandled rejections) or relying on execution order of
asynchronous tasks.
Interview tip: Emphasize non-blocking I/O and responsiveness (especially in browser UIs / Node
servers).
Definition: The runtime mechanism that coordinates executing JS code, handling events, and running
queued tasks in a single-threaded environment.
Behavior: Repeatedly takes tasks from macrotask queue (task queue), executes them on the call
stack, then drains microtask queue before rendering and before next macrotask.
Example flow: Script → call stack empties → process microtasks (promise .then) → render → next
macrotask (e.g., setTimeout).
Pitfall: Misunderstanding microtasks vs macrotasks leads to wrong assumptions about order of
execution.
Definition: Another name for the macrotask (task) queue — where callbacks scheduled
via setTimeout, setInterval, I/O callbacks, and UI events are queued.
Behavior: Event loop pulls from this queue when the call stack is empty and after microtasks have
been processed.
Pitfall: Heavy synchronous code can starve the callback queue and make UI unresponsive.
Definition: Tasks queued in the callback (task) queue — e.g., setTimeout, setInterval, I/O callbacks,
DOM events.
Behavior: Processed one at a time, after current script finishes and after microtasks processed.
Pitfall: Assuming setTimeout(fn, 0) runs immediately — it’s a macrotask and will run after microtasks
and rendering.
6. What is a callback?
7. What is promise?
8. What is async/await?
Definition: Syntactic sugar over promises that lets you write asynchronous code in a synchronous
style using async functions and await expressions.
Example:
Pitfall: await blocks only the async function, not the whole thread; using await in loops can cause
serial execution — use [Link] for concurrency when safe.
Interview tip: Explain error handling (try/catch or .catch) and concurrency patterns (await
[Link]([...])).
9. What is fetch?
Definition: Modern web API (Promise-based) for making network requests (replaces older XHR in
many uses).
Example: fetch('/api').then(res => [Link]()).
Pitfall: fetch only rejects on network failure — HTTP errors like 404/500 still resolve; you must
check [Link].
Interview tip: Mention streaming responses and [Link]() for large responses.
Definition: Asynchronous JavaScript and XML — pattern/technique for making asynchronous HTTP
requests from the browser. Historically used with XMLHttpRequest.
Behavior: Can fetch JSON, HTML, XML — modern code usually uses fetch or libraries (axios).
Interview tip: Emphasize that AJAX is a technique, not a specific API.
Definition: Older browser API for HTTP requests; works with callbacks and events
(onreadystatechange).
Example:
Definition: JSON with Padding — a legacy technique to bypass cross-origin restrictions by injecting
a <script> tag that calls a global callback with data.
Pitfall: Security risk (remote script execution) and limited to GET requests. Superseded by CORS and
modern APIs.
Interview tip: Explain why CORS replaced JSONP.
Definition: Cross-Origin Resource Sharing — browser security mechanism that allows servers to
instruct browsers which origins are permitted to access resources.
Behavior: Server sets headers like Access-Control-Allow-Origin, Access-Control-Allow-Methods.
Browsers enforce it automatically.
Pitfall: Misconfiguring CORS can expose APIs or block legitimate requests; preflight requests
(OPTIONS) happen for certain requests.
Interview tip: Mention Access-Control-Allow-Credentials for cookies and same-site considerations.
What is throttling?
Definition: Limit how frequently a function runs — ensures a function executes at most once per
specified interval. Useful for scroll/resize events.
Example use-case: Update position/display at most every 100ms.
Pitfall: Throttling can delay the last call; choose behavior (leading/trailing) intentionally.
Interview tip: Compare to debouncing.
Definition: Delay function execution until a certain time has passed since the last call — useful for
search inputs to wait for user pause.
Example: Only send search request 300ms after user stops typing.
Pitfall: If you need the function to run at start of burst, configure leading invocation; otherwise
default trailing behavior works.
Interview tip: Explain both use-cases: debouncing (typing), throttling (scrolling).
Definition: Receiving response body in chunks as they arrive (instead of waiting for full body) using
Streams API — enables progressive parsing/display.
Example: const reader = [Link]() and consume chunks.
Pitfall: Handling backpressure, chunk assembly, and partial encodings can complicate logic.
Interview tip: Useful for large files, progressive rendering, or server-sent chunked outputs.
Definition: An object conforming to the async iterable protocol ([[Link]]) allowing for
await...of to iterate over asynchronous data streams.
Example:
Definition: Bidirectional streaming where both client and server can read and write streams
simultaneously. Common in protocols like HTTP/2, WebSocket, and gRPC.
Behavior: Allows efficient large data exchange without waiting for entire payloads.
Pitfall: Complexity in flow control and backpressure management.
Definition: In the context of JS event loop, job queue is another name for the microtask queue —
short jobs scheduled during runtime (promises). Some runtimes may expose additional job/task
queues for scheduling.
Interview tip: Clarify microtasks vs macrotasks again if asked.
Definition: Browser recalculation of layout when DOM geometry changes (e.g., element
size/position). Also called layout.
Cost: Expensive — can trigger repaint and be slow on complex pages.
Pitfall: Frequent DOM reads/writes that force reflow (like offsetWidth after DOM changes). Batch
DOM writes or use requestAnimationFrame.
Definition: When styles that don’t affect layout (color, visibility) change, the browser repaints pixels
without recalculating layout. Cheaper than reflow.
Pitfall: Still costly if done often; combine with transform/opacity animations to avoid layout
thrashing.
Definition: Process in SSR frameworks where server-rendered HTML is “wired up” with client-side JS
to become interactive — the client attaches event listeners and restores state.
Pitfall: Large hydration bundles can be slow; partial hydration and island architectures can help.
Interview tip: Compare hydration with CSR full client rendering.
Definition: Rendering HTML on server and sending fully-formed pages to clients, improving initial
load time and SEO.
Benefits: Faster first paint, indexable by crawlers.
Pitfall: May require additional server resources and complexity for reactivity/hydration.
Definition: Client downloads JS bundle then renders content on the client — initial HTML is minimal.
Benefits: Rich client apps and SPA patterns.
Pitfall: Slower initial paint and worse SEO unless SSR/hydration used.
Definition: Restrict number of requests a client can make in a time window to prevent abuse and
ensure fair usage.
Strategies: Token bucket, leaky bucket, fixed window.
Pitfall: Overly aggressive limits may degrade UX; need to communicate limits (headers) and allow
retries.
38. What is network throttling?
Definition: Simulating slower network conditions (e.g., 3G) to test performance and user
experiences. DevTools offer network throttling.
Interview tip: Use to test loading patterns, lazy-loading and bundle sizes.
Definition: An OPTIONS request browser sends before certain CORS requests to check server’s
allowed methods/headers.
Pitfall: Increases latency; minimize custom headers or use simple requests when possible.
Definition: Data structure where each element has a priority; higher-priority elements are served
before lower-priority ones.
Use in web: Scheduling urgent tasks (e.g., UI updates) before lower-priority background tasks.
Interview tip: In HTML5/JS task scheduling, browsers may prioritize input/animation tasks over other
tasks.
2. What is querySelector?
3. What is querySelectorAll?
5. What is classList?
6. What is dataset?
8. What is bubbling?
9. What is capturing?