[Go to site: main page, start]

0% found this document useful (0 votes)
2 views25 pages

Java Script

JavaScript is a high-level, dynamic programming language used for web interactivity and supports various programming paradigms. It features primitive types, hoisting, closures, and asynchronous programming through callbacks and promises, while also providing tools for DOM manipulation and event handling. Key concepts include the event loop, call stack, higher-order functions, and array methods like map, filter, and reduce.

Uploaded by

thanujasoma2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

Java Script

JavaScript is a high-level, dynamic programming language used for web interactivity and supports various programming paradigms. It features primitive types, hoisting, closures, and asynchronous programming through callbacks and promises, while also providing tools for DOM manipulation and event handling. Key concepts include the event loop, call stack, higher-order functions, and array methods like map, filter, and reduce.

Uploaded by

thanujasoma2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript is a high-level, dynamic, interpreted programming language primarily used for adding

interactivity to web pages (running in browsers). It’s prototype-based, multi-paradigm (procedural,


functional, object-oriented styles), and has first-class functions. Modern JavaScript (ES6+) is also used
server-side ([Link]), for desktop/mobile apps, and tooling. It executes in an event-driven
environment and provides APIs for DOM manipulation, networking (fetch/XHR), timers, etc.

Java typically uses threads and locking. JavaScript uses a single-threaded event loop with
asynchronous callbacks, promises, and async/await.

Primitive types (7 in modern JS):

Primitive types are immutable

string — textual data ("hello")

number — numeric values (floating point and integer; NaN, Infinity are number)

bigint — integers of arbitrary size (123n)

boolean — true or false

undefined — a variable declared but not assigned

null — explicit “no value” / empty

symbol — unique identifiers

Non-primitive / Reference type:

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.

How to explain it simply:

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() {

[Link]("Initial snapshot:", value);

var value = 5;

return function() {

value += 5;

[Link]("Current value:", value);

};
}

const myFunc = createIncrementer();

myFunc();

myFunc();

Initial snapshot: undefined

Current value: 10

Current value: 15

greet(); // Works! Outputs: "Hello!"

[Link](username); // Works! Outputs: undefined

[Link](age); // CRASH! ReferenceError: Cannot access 'age' before initialization

function greet() { [Link]("Hello!"); }

var username = "Alex";

let age = 25;

undefined means a variable has been declared but not assigned; it’s often produced by the runtime

null is a primitive value that represents the intentional absence

typeof null returns "object" due to a historical quirk

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)

typeof NaN is "number"

[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

Function-scoped (or global if declared outside functions).

Hoisted and initialized to undefined.

Allows re-declaration in same scope

• let

Block-scoped (between {}).

Hoisted to TDZ — accessing before declaration throws ReferenceError.

Can be reassigned but not redeclared in the same scope.

• const

Block-scoped.

Must be initialized at declaration; cannot be reassigned.

For objects/arrays, the binding is constant (reference), but object properties or array items can be
mutated

In browsers the global object is window or globalThis in modern JS

Template literals (ES6) are string literals enclosed by backticks (`) that can contain placeholders,
multi-line text, and embedded expressions.

Interpolation means embedding expressions inside template literals using ${expression}

Example:

const name = 'Asha';


const greeting = `Hello, ${name}!`; // interpolation
const multi = `line1
line2`; // multi-line

const a = 2, b = 3;
`${a} + ${b} = ${a + b}` // "2 + 3 = 5"

How to create arrays?

• const arr = [1, 2, 3]; (recommended)

• [Link](1, 2, 3)

• new Array(3) → creates an array with length 3 (sparse)

• From iterable: [Link]('abc')

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

• 1 + '2' → '12' (number coerced to string)

• '5' * 2 → 10 (string coerced to number)

• if ('') → false

null == 0 → false, but null == undefined → true

• 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],

Browser Object Model (BOM)

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.

2. Executes it (call stack).


3. After the stack is empty, it processes microtasks (like resolved promise callbacks) —
microtasks run before the next macrotask.
This model allows non-blocking I/O and concurrency-like behavior in a single thread.

Call stack — currently executing functions.

Microtask queue — [Link], queueMicrotask callbacks; processed after current stack frame
but before next macrotask.

Macrotask queue — setTimeout, setInterval, I/O callbacks, UI rendering tasks.

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.

[Link] often contains the trace -> stack trace

A function is a reusable block of code that performs a task or computes a value.

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.

const greet = function(name) {


return `Hi ${name}`;
};

Default parameters let you specify default values for parameters when arguments are undefined.

function greet(name = 'Guest') {


return `Hello, ${name}`;
}
greet(); // "Hello, Guest"

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

Use cases of closures?

• Data encapsulation / private state (module patterns)

• Factory functions that produce configured functions

• Event handlers capturing variables from outer scope

• Memoization (keeping cache)

• Partial application / currying (holding some args)

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');
})();

A higher-order function either takes functions as arguments, returns a function, or both.


Examples: map, filter, reduce.

const twice = fn => x => fn(fn(x));

A callback is a function passed to another function to be invoked later (synchronously or


asynchronously).

setTimeout(() => [Link]('Later'), 1000);

Nested callbacks can lead to “callback hell”; prefer Promises/async-await.

Currying transforms a function with multiple arguments into a sequence of functions each taking a
single argument.

const add = a => b => a + b;


add(2)(3); // 5

Partial application fixes some arguments of a function and returns a new function expecting the
remaining arguments.

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


const add5 = a => b => add(a, b); // partialish

Or using bind:

const add5 = [Link](null, 5);


add5(3); // 8

Distinction: Currying breaks args into unary functions; partial application fixes specific args and
returns a function awaiting the rest.

15. What is recursion?

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).

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

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'

Tip: Distinguish prototype (for instances) vs __proto__ (internal link).

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
});
});
});

Solution: Promises, async/await, modularization

An async function returns a Promise. Inside you can use await to pause execution until a Promise
resolves. Errors thrown become rejected Promises.

async function fetchData() {


const res = await fetch('/api');
return [Link]();
}

What does map() do?

[Link]() creates a new array by applying a provided function (mapper) to every


element of the source array. It does not mutate the original array.

Example:

const nums = [1, 2, 3];


const doubled = [Link](x => x * 2); // [2, 4, 6]

Notes & gotchas:

• Returns an array of the same length as the input.

• Callback receives (value, index, array).

• 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.

2. What does filter() do?

[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:

const nums = [1, 2, 3, 4];


const evens = [Link](n => n % 2 === 0); // [2, 4]
Notes:

• Output length ≤ input length.

• Predicate receives (value, index, array).

• Use for selecting a subset of elements.

3. What does reduce() do?

[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:

[Link]((accumulator, currentValue, index, array) => newAccumulator, initialValue)

Example (sum):

const nums = [1, 2, 3];


const sum = [Link]((acc, n) => acc + n, 0); // 6

Use cases:

• Sum, product, flattening, grouping, building maps or objects.

• 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).

4. Difference between find vs filter?

• find(predicate) returns the first element that satisfies the predicate, or undefined if none
match.

• filter(predicate) returns an array of all matching elements (possibly empty).

Example:

const arr = [1,2,3,4];


[Link](n => n > 2); // 3
[Link](n => n > 2); // [3, 4]

Choose find when you need a single match; filter for multiple.

5. What does some() do?

[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:

const arr = [1, 2, 3];


[Link](n => n === 2); // true

Use for membership-like checks or validating conditions.

6. What does every() do?


[Link]() tests whether all elements pass the predicate. Returns true if every element
satisfies the test (including the edge case of an empty array, which returns true). Short-circuits on
first falsy result.

Example:

[2,4,6].every(n => n % 2 === 0); // true


[].every(() => false); // true (vacuously true)

7. What does flat() do?

[Link](depth = 1) returns a new array with sub-array elements concatenated into


it recursively up to the specified depth.

Example:

const nested = [1, [2, [3, 4]]];


[Link](); // [1, 2, [3,4]]
[Link](2); // [1, 2, 3, 4]
[Link](Infinity); // fully flattened

Notes:

• Does not mutate original array.

• Browser support is modern — polyfill may be needed for older environments.

8. What does flatMap() do?

[Link](fn) is equivalent to [Link](fn).flat(1) — it maps each element using fn and


then flattens the result by 1 level.

Example:

const words = ["hello world", "foo bar"];


[Link](s => [Link](" ")); // ["hello", "world", "foo", "bar"]

Use when mapping returns arrays and you want a single flattened array as the result.

9. What is array destructuring?

Array destructuring assigns variables from array positions in a concise syntax.

Example:

const arr = [1, 2, 3];


const [a, b] = arr; // a=1, b=2
const [first, ...rest] = arr; // rest = [2,3]

Use cases:

• Readable extraction of elements, function returns, swapping:

let x = 1, y = 2;
[x, y] = [y, x]; // swap

10. What is object destructuring?


Object destructuring extracts properties by name into variables.

Example:

const obj = { name: "A", age: 30 };


const { name, age } = obj; // name="A", age=30
// with renaming
const { name: fullName } = obj;

Notes:

• Order doesn’t matter; names must match property keys.

• You can provide defaults: const { x = 0 } = maybe;

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:

const user = {};


[Link]([Link]?.email); // undefined (no exception)
[Link]?.(); // safe call if getName exists

Use to avoid lots of && checks for deep property access. Be mindful optional chaining short-circuits
only on null/undefined.

12. What is nullish coalescing?

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:

const a = 0 ?? 5; // 0 (since 0 is not null/undefined)


const b = null ?? 5; // 5
const c = "" || "fallback"; // "fallback" (because "" is falsy)

Use when you want to provide defaults only for null/undefined, not for other falsy values.

13. What is shorthand object?

Shorthand property syntax creates object properties with names equal to variable names.
Example:

const name = "A", age = 30;


const person = { name, age }; // same as { name: name, age: age }

Also works with methods:

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:

{"name": "Alice", "age": 30, "tags": ["dev","js"]}

Notes:

• JSON keys must be double-quoted strings.

• Only supports a subset of JS types: objects, arrays, strings, numbers, true, false, null.
Functions and undefined are not representable.

16. What is [Link]?

[Link](value, replacer?, space?) converts a JavaScript value to a JSON string.

Example:

[Link]({ a: 1 }); // '{"a":1}'


[Link]([1,2,3]); // '[1,2,3]'

Options:

• replacer: function or array to control what/how values are serialized.

• space: indentation for pretty-printing.

Gotcha:

• undefined, functions, and symbols are omitted (or converted to null in arrays).

• Circular references throw.

17. What is [Link]?

[Link](text, reviver?) parses a JSON string and returns the corresponding JavaScript value.

Example:

const obj = [Link]('{"a":1}'); // { a: 1 }

reviver can transform values during parsing.

18. What is deep clone?


Deep clone creates a new object with recursively copied nested objects/arrays, so mutations to the
clone do not affect the original.

Naive example (limitations):

const clone = [Link]([Link](obj));

This works for simple data (no functions, Dates, undefined, Maps, Sets, or circular refs), but fails on
those types.

Robust deep clone approaches:

• Custom recursive clone handling special types.

• Use structured cloning (structuredClone(obj) in modern environments) — supports many


types and handles cycles.

19. What is shallow clone?

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 } };

const shallow = { ...obj }; // spread

const shallow2 = [Link]({}, obj);

shallow.b === obj.b; // true (same reference)

Use shallow clone when nested mutations are not a concern; otherwise use deep cloning.

[Link]({a:1, b:2}); // ["a", "b"]

[Link]({a:1, b:2}); // [1, 2]

[Link]({a:1}); // [["a", 1]]

[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 }

Using the spread operator (...) to copy or expand arrays.

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 }

Order matters for overwrites: { ...a, ...b }.

[Link](obj) makes an object immutable: you cannot add, remove, or change its existing
properties (shallow freeze). It returns the same object.

Example:

const o = [Link]({ a: 1 });


o.a = 2; // ignored in non-strict, throws in strict mode

Note:

• Shallow only — nested objects remain mutable. For deep immutability, recurse and freeze
nested objects

[Link](obj) prevents adding or removing properties


but allows modification of existing properties (unless they are
non-writable). It also marks all properties as non-configurable.
Example:

• const o = { a: 1 };
[Link](o);
o.b = 2; // ignored / fails
o.a = 3; // allowed

How to merge arrays?

Common ways:

• Using spread: const merged = [...a, ...b]

• Using concat: const merged = [Link](b)

• In-place push: [Link](...b) (mutates a)

Example:

const a = [1,2], b = [3,4];


const merged = [...a, ...b]; // [1,2,3,4]
36. How to merge objects?

Common ways:

• Spread (recommended for shallow merge):

const merged = { ...obj1, ...obj2 }; // later keys overwrite earlier ones

• [Link]():

const merged = [Link]({}, obj1, obj2);

Notes:

• Both are shallow merges. Nested objects are referenced, not deep-merged.

• For deep merges use libraries (Lodash _.merge) or custom recursive merge.

37. What is [Link]()?

[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

Useful for converting iterables and generics to proper arrays.

38. What is [Link]()?

[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)

Use when you want predictable creation.

39. What is destructuring in functions?

You can destructure parameters directly in function signatures for clarity.

Examples:

• Object param destructuring with defaults:

function greet({ name = "Guest", age } = {}) {


[Link](name);
}
greet({ name: "A" });

• Array parameter destructuring:


function sum([a, b]) { return a + b; }
sum([1,2]); // 3

Benefits:

• Cleaner extraction of needed fields, default values, and reduces boilerplate inside function.

40. What are array-like objects?

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.

You can convert them to real arrays:

const real = [Link](arrayLike);

Or use [Link](arguments) in older code.

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

const declares a block-scoped binding that cannot be reassigned. It must be initialized at


declaration. For objects/arrays the binding is constant, but object properties or array contents can be
mutated.

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:

const p = new Promise((resolve, reject) => {


setTimeout(() => resolve(42), 100);
});
[Link](val => [Link](val));

13. What is promise chaining?

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));

14. What is [Link]()?

[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]([p1, p2]).then(([r1,r2]) => {});

Gotcha: If any promise rejects, the whole [Link] rejects.

15. What is [Link]()?

[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 => ...);

16. What is [Link]()?

[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

17. What is [Link]()?

[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:

[Link]([p1, p2]).then(results => [Link](results));

18. What is template literal?

Template literals use backticks (`) to create strings that


support interpolation ${expr}, multiline strings, and tagging (tagged templates). They replace
awkward concatenation with readable syntax.
const name = 'A';
const msg = `Hello ${name}\nNext line`;

19. What is destructuring?

Destructuring extracts values from arrays or properties from objects into separate variables
succinctly.

Array:

const [a,b] = [1,2]; // a=1, b=2

Object:

const {x, y: alias} = {x:1, y:2}; // x=1, alias=2

1. What is async programming?

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).

What is event loop?

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.

What is callback queue?

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.

What is microtask queue?


Definition: A high-priority queue for short tasks that must run immediately after the current stack
frame finishes — includes resolved Promise callbacks (.then, .catch, .finally) and queueMicrotask.
Behavior: Microtasks are processed before the event loop moves on to the next macrotask and
before rendering.
Pitfall: Creating many microtasks can block rendering and starve UI updates.
Interview tip: Use a microtask example: [Link]().then(() => [Link]('micro')) runs
before a setTimeout(...,0) callback

What are macrotasks?

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?

Definition: A function passed as an argument to be invoked later, usually after an asynchronous


operation completes.
Example: [Link](path, (err, data) => { /* callback */ }) in Node or [Link]('click',
() => {}) in browser.
Pitfall: Nested callbacks can lead to “callback hell” (deep nesting and hard-to-manage flows).
Interview tip: Mention alternatives: Promises, async/await, observables.

7. What is promise?

Definition: An object representing eventual completion (fulfillment) or failure (rejection) of an async


operation.
States: pending → fulfilled or rejected.
Example: new Promise((resolve, reject) => { /* async */ }). Use .then, .catch, .finally.
Pitfall: Not returning promises from .then handlers leads to unintended behavior; unhandled
rejections.
Interview tip: Explain promise chaining and error propagation.

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:

async function getData() {


try {
const res = await fetch('/api');
const data = await [Link]();
return data;
} catch (e) { /* handle */ }
}

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]([...])).

— Networking & browser APIs

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.

10. What is AJAX?

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.

11. What is XHR (XMLHttpRequest)?

Definition: Older browser API for HTTP requests; works with callbacks and events
(onreadystatechange).
Example:

const xhr = new XMLHttpRequest();


[Link]('GET', '/api');
[Link] = () => { [Link]([Link]); };
[Link]();

Pitfall: Verbose and callback-based; fetch is preferred in modern code.

12. What is JSONP?

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.

13. What is CORS?

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.

Difference between timeout & interval?


setTimeout: schedules a single execution after delay.
setInterval: schedules repeated execution at given interval until cleared.
Pitfall: setInterval callbacks can overlap if the task takes longer than the interval — prefer
recursive setTimeout for variable durations

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.

26. What is 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).

27. What is streaming response?

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.

28. What is async iterator?

Definition: An object conforming to the async iterable protocol ([[Link]]) allowing for
await...of to iterate over asynchronous data streams.
Example:

for await (const chunk of asyncStream) {


// process each chunk as it arrives
}

Pitfall: Requires environment with async iterator support or transpilation.


Interview tip: Mention combining Streams API with for await.

29. What is duplex streaming?

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.

30. What is job queue?

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.

— Performance & rendering

31. What is reflow?

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.

32. What is repaint?

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.

33. What is hydration?

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.

34. What is SSR (Server-Side 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.

35. What is CSR (Client-Side Rendering)?

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.

36. What is caching?

Definition: Storing resources (responses, computed values) to avoid refetching or recomputing.


Implemented at browser/cache-control, service worker, in-memory, or CDN levels.
Pitfall: Cache invalidation complexity; stale data if not versioned.
Interview tip: Mention strategies: cache-control headers, ETag, stale-while-revalidate.

37. What is rate limiting?

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.

39. What are preflight requests?

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.

40. What is priority queue?

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.

1. What is DOM tree?

2. What is querySelector?

3. What is querySelectorAll?

4. Difference between innerHTML and textContent?

5. What is classList?

6. What is dataset?

7. What is event listener?

8. What is bubbling?

9. What is capturing?

10. What is stopPropagation?

11. What is preventDefault?

12. What is createElement?

13. What is append?

14. What is appendChild?

15. What is removeChild?

16. What is cloneNode?

17. What is shadow DOM?

18. What is virtual DOM?

19. What is intersection observer?

20. What is mutation observer?


21. What is resize observer?

22. What is cookies?

23. What is sessionStorage?

24. What is localStorage?

25. What is HttpOnly cookie?

26. What is SameSite cookie?

27. What is CSP?

28. What is clickjacking?

29. What is iframe sandbox?

30. What is browser plugin?

31. What is navigation timing?

32. What is resource timing?

33. What is user timing?

34. What is performance API?

35. What is layout thrashing?

36. What is repaint?

37. What is reflow?

38. What is browser hydration?

39. What is lazy loading?

40. What is preloading?

You might also like