javascript theory
javascript theory
A Java Script engine is a program that present in web browsers that exicutes
JavaScript code.
o Server side
Template literals are enclosed by backticks (```) instead of single (') or double (")
quotes.
String interpolation allows you to embed variables or expressions inside a string. With
template literals, you can insert these expressions directly using ${}.
Operators ?
o Arithmetic operator
+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulus (Remainder)
++ : Increment
--: Decrement
o Comparison operator
== : Equal to
!= : Not equal to
=== : Strict equal (value and type)
!== : Strict not equal
> : Greater than
< : Less than
>= : Greater than or equal to
<= : Less than or equal to
o Logical operator
&& : Logical AND
|| : Logical OR
! : Logical NOT
o Assignment operator
= : Assignment
+= : Add and assign
= : Subtract and assign
= : Multiply and assign
/= : Divide and assign
%= : Modulus and assign
o String operator
Type of operator ?
**Use :**Type of operator can be used to validate the data received from external
sources(api)
Type coercion is the automatic conversion of values from one data type to another
during certain operations or comparisons.
o Implicit Coercion:
let num = 10; let str = 'The number is ' + num; // 'The
number is 10'
o Explicit Coercion:
Explicit Coercion: Happens when you manually convert a value from one
type to another using built-in functions or operators.
Conditions statements ?
o if Statement
o if...else Statement
o else if Statement
if (condition1) { // code to be executed if condition1 is true } else if
(condition2) { // code to be executed if condition2 is true } else { // code to be
executed if both conditions are false }
o Switch Statement
o let day = 2;
o let dayName;
o
o switch(day) {
o case 1:
o dayName = "Monday";
o break;
o case 2:
o dayName = "Tuseday";
o break;
o default:
o dayName = "NO DAY";
o };
o console.log(dayName);
o Ternary Operator
Selectors in JS?
Selectors in JS helps to get specific element from DOM based on by ID names, class
names, tag names.
Loops allow you to execute a block of code repeatedly until a specified condition is
met.
It allows you to iterate over the keys of an object and access the values
associated by using keys as the index.
const person = {
name: "Ai",
age: 20,
place: "RRR"
};
o for of : Used to loop through the values of an object like arrays or strings.
It allows you to access each values directly without having to use an index
Function ?
Function is a reusable block of code which use to perform a specific task. A function
declared using the function keyword.
o Named Functions
function sayHello() {
console.log("Hello!");
}
o Function Expression
o Anonymous Function
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
o Arrow Function
A shorter syntax introduced in ES6 for writing functions, with a more concise
function declaration.
o Callback Function
A callback function is a function that is passed as an argument to another
function. Is executed inside that function after some kind of event or
condition.
Why Use Callbacks? Callbacks are used to ensure that a function is executed
only after another function has finished executing, which is especially useful
in asynchronous operations like API calls or event handling.
function sayGoodbye() {
console.log("Goodbye!");
}
o Higher-Order Function
Takes one or more functions as arguments, or
o function hof ( fun ) {
o
o fun ();
o }
o hof ( sayHello ) ;
o
o function sayHello () {
o console.log( “Hello” );
o }
o
o //output “Hello”
Returns a function as its result.
o function createAdder ( number ) {
o return function ( value ) {
o return value + number;
o };
o }
o First-Class Functions
Be assigned to variables.
(function() {
// Your code here
})();
(function() {
var message = "This is an IIFE!";
console.log(message);
})();
o Math Function
Math.round(): Rounds a number to the nearest integer.
console.log(Math.round(4.7)); // Output: 5
console.log(Math.round(4.3)); // Output: 4
console.log(Math.ceil(4.1)); // Output: 5
console.log(Math.ceil(4.9)); // Output: 5
console.log(Math.floor(4.9)); // Output: 4
console.log(Math.floor(4.1)); // Output: 4
console.log(Math.sqrt(16)); // Output: 4
console.log(Math.sqrt(25)); // Output: 5
console.log(Math.abs(-5)); // Output: 5
console.log(Math.abs(3)); // Output: 3
Always produces the same output for the same inputs. Has no side effects,
meaning it doesn’t modify any state outside the function or perform any
observable changes like modifying global variables, logging to the console, or
altering data outside its scope.
function add(a, b) {
return a + b; // The same inputs will always give the same
result.
}
o Impure Function
function increment() {
count += 1; // Changes external state (impure)
return count;
}
console.log(increment()); // Output: 1
console.log(increment()); // Output: 2 (same function call,
but different output)
Explanation
First gen.next() → Runs until yield 1 → Returns 1 and
pauses.
Second gen.next() → Resumes after yield 1 → Runs until
yield 2 → Returns 2 and pauses.
Third gen.next() → Resumes after yield 2 → Runs until
yield 3 → Returns 3 and pauses.
Fourth gen.next() → Since no more yield statements
remain, it returns { value: undefined, done: true }.
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = numberGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
console.log(gen.next().done); // true (generator is
done, no more yields)
o Factory Function
o eval() Function
Currying ?
Arguments are the actual values or expressions passed to the function when it
is called.
o Parameters
Default Parameter ?
Default parameters allow you to specify default values for function parameter.
call(), apply(), and bind() are methods in JavaScript used to invoke a function
with a specific this context.
o Call
call(): Invokes a function, passing this and arguments individually.
Syntax: functionName.call(thisArg, arg1, arg2, ...)
o function describe( message ) {
o console.log( `${message}, ${this.name} ! `);
o }
o
o const person = { name: "Alice" };
o
o // Using call to invoke describe with different objects
o describe.call( person, “Hey” ); // Outputs: Hey Alice
o Apply
apply(): Invokes a function, passing this and arguments as an array.
Syntax: functionName.apply(thisArg, [arg1, arg2, ...])
o function describe( message ) {
o console.log( `${message}, ${this.name} ! `);
o }
o
o const person = { name: "Alice" };
o
o // Using call to invoke describe with different objects
o describe.apply( person, ['hi'] ); // Outputs: hi Alice
o Bind
bind(): Returns a new function with a specific this value and preset
arguments for later use.
Syntax: functionName.bind(thisArg, arg1, arg2, ...)
o function describe( message ) {
o console.log( `${message}, ${this.name} ! `);
o }
o
o const person = { name: "Alice" };
o
o // Using call to invoke describe with different objects
o
o const greetPerson = discribe.bind( person );
o
o greetPerson( ` Greetings` );
o // Outputs: Greetings, Alice
Array ?
Arrays in JavaScript are collections of items, and they can hold any type of data.
o Array Methods
Get
filter(): Creates a new array with all elements that pass a
test.
let numbers = [1, 2, 3, 4];
let even = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(even); // Output: [2, 4]
slice(): Extracts a section of an array and returns a new array.
let fruits = ["apple", "banana", "cherry", "date"];
let slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ["banana",
"cherry"]
Modify
forEach(): Executes a function for each element in the array.
Others
length: Returns the number of elements in an array.
array.flat(depth);
o Array-like object ?
Array-like object are objects that have indexed elements and a length
property , similar to arrays but they may not have all the methods of array like
push (), pop () & others.
eg:
Array vs Set ?
Array destructuring ?
Array Expansion:
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // [1, 2, 3, 4, 5]
Object Expansion:
const person = { name: "Alice", age: 25 };
const updatedPerson = { ...person, city: "New York" };
console.log(updatedPerson); // { name: "Alice", age: 25,
city: "New York" }
Function Arguments:
const sum = (a, b, c) => a + b + c;
const nums = [1, 2, 3];
console.log(sum(...nums)); // 6
Use:
Copying an Array
Merging Array
o Rest
display(1, 2, 3, 4, 5);
Objects ?
Object methods ?
o Object.assign(): Copies properties from one or more source objects to a
target object.
Method Description
Object.keys() Gets an array of object keys.
Object.values() Gets an array of object values.
Object.entries() Gets an array of key-value pairs.
Object.assign() Copies properties from source to target.
Object.freeze() Freezes an object to make it immutable.
Object.seal() Seals an object, disallowing new properties.
Object.hasOwnProperty() Checks if a property exists in an object.
Object.is() Checks if two values are the same.
Object.defineProperty() Defines a single property.
Object.defineProperties() Defines multiple properties.
Object.create() Creates a new object from a prototype.
Object shorthand ?
Object shorthand is a convenient way to create objects when you want the property
name to be the same as the variable name.
Object.freeze vs Object.seal ?
Both Object.freeze() and Object.seal() are methods to control how objects can be
modified, but they behave slightly differently:
o Object.freeze
o const obj = { name: "Alice", age: 25 };
o
o Object.freeze(obj);
o
o obj.name = "Bob"; // Not allowed (modification)
o delete obj.age; // Not allowed (removal)
o obj.city = "NY"; // Not allowed (addition)
o
o console.log(obj); // { name: "Alice", age: 25 }
o
o Object.seal
o const obj = { name: "Alice", age: 25 };
o
o Object.seal(obj);
o
o obj.name = "Bob"; // Allowed (modification)
o delete obj.age; // Not allowed (removal)
o obj.city = "NY"; // Not allowed (addition)
o
o console.log(obj); // { name: "Bob", age: 25 }
o
Feature Object.freeze() Object.seal()
Prevents property
Yes Yes
additions
Prevents property
Yes Yes
deletions
Prevents modification of No (existing properties can still be
Yes
existing properties modified)
Prevents changes to
Yes Yes
property descriptors
Fully lock down the Allow modifications but prevent
Use case
object. adding/removing properties.
Optional Chaining ?
Optional Chaining is a feature in JavaScript that allows safe access to deeply nested
properties of an object without having to explicitly check each level for null or
undefined. If any property in the chain is null or undefined, it short-circuits and
returns undefined instead of throwing an error.
const user = {
name: "Alice",
address: {
city: "Paris"
}
};
Short-circuit ?
The process where the evaluation of a logical expression is stopped as soon as the
result is determined. This behavior occurs primarily with the logical operators &&
(AND) and || (OR).
1. Logical OR (||):
2. const a = true;
3. const b = false;
4.
5. const result = a || (b = true); // b is not evaluated or
assigned
6. console.log(result); // true
7. console.log(b); // false (remains unchanged)
8. Logical AND (&&):
9. const a = false;
10. const b = true;
11.
12. const result = a && (b = false); // b is not evaluated or
assigned
13. console.log(result); // false
14. console.log(b); // true (remains unchanged)
Null Coalescing (Nullish operator)?
The Nullish Coalescing Operator (??) is used to return the right-hand operand if
the left-hand operand is null or undefined. It is similar to the || operator, but the
key difference is that || considers false, 0, '', and NaN as falsy values, whereas ??
only considers null and undefined.
Prototypes ?
A Set object is a collection of unique values, means there are no duplicate values.
mySet.add(1);
mySet.add(2);
mySet.add(2); // Duplicate value, will be ignored
console.log(mySet); // Outputs: Set { 1, 2 }
Key ?
A key refers to the property name inside an object. It is used to access the
corresponding value in a key-value pair.
let person = {
name: "Alice", // 'name' is the key, "Alice" is the value
age: 25, // 'age' is the key, 25 is the value
isStudent: true // 'isStudent' is the key, true is the value
};
Map ?
Map is a collection of key-value pairs where both the keys and values can be of any
type.
Method/Property Description
set(key, value) Adds or updates a key-value pair.
get(key) Retrieves the value associated with a key.
has(key) Checks if a key exists in the Map.
delete(key) Removes a key-value pair.
clear() Removes all key-value pairs.
size Returns the number of key-value pairs.
forEach() Iterates over the key-value pairs in the Map.
A WeakSet is a collection of objects where each object can only appear once,
and the references to these objects are weak. If no other reference to an object
stored in the WeakSet exists, the object can be garbage-collected, meaning it
doesn't prevent memory from being freed.
Use of Strict ?
Strict Mode makes it easier to catch common coding errors and prevents the usage
of unsafe features in JavaScript.
classes are a template for creating objects. They encapsulate data and functionality in
a neat, reusable structure. The constructor is a special method inside a class that is
used for initializing new objects (instances) of that class.
Use :
Callback Queue ?
Callback Queue: Handles tasks like setTimeout, setInterval, DOM events, and
other asynchronous operations.
Microtask Queue ?
Microtask Queue: Handles tasks like Promises and async/await, which are designed
to run after the current code but before the callback queue.
Promises ?
o Code
o const myPromise = new Promise((resolve, reject) => {
o // Simulating asynchronous operation
o const success = true;
o
o if (success) {
o resolve("Task completed successfully!");
o } else {
o reject("Task failed!");
o }
o });
o myPromise
o .then((message) => {
o console.log(message); // If resolved, it prints the
success message
o })
o .catch((message) => {
o console.log(message); // If rejected, it prints the error
message
o });
resolve is called when the task is successful, which changes the
promise’s state to fulfilled.
reject is called when the task fails, which changes the promise’s state
to rejected.
o Use
API calls
File handling
Data fetching
Consuming Promises ?
Promise chaining is a technique in JavaScript where you use the result of one
promise and pass it to another .then() block, creating a sequence of asynchronous
operations. Each .then() in the chain returns a new promise, allowing you to handle
results step-by-step.
o Example
o const myPromise = new Promise((resolve, reject) => {
o const success = true;
o if (success) {
o resolve({ name: "Ai", age: 21 });
o } else {
o reject("User not found");
o }
o });
o
o myPromise
o .then((result) => {
o console.log(`User name: ${result.name}`);
o return result.age;
o })
o .then((age) => {
o console.log(`User age: ${age}`);
o })
o .catch((error) => {
o console.log(error);
o });
promise
.then(result => {
// Process result
return nextPromise; // Return a new promise
})
.then(nextResult => {
// Process nextResult
return anotherPromise;
})
.catch(error => {
// Handle any error in the chain
});
Promise combinator
eg:
o Promise.all()
o Promise.allSettled()
o Promise.race()
o Promise.any()
Promise.all () ?
Promise.any () ?
Promise.race() ?
1. Promise.race() is used to handle multiple promises concurrently.
2. Promise.race() takes an array of promises as input parameter and returns a
single promise.
3. Promise.race() waits for only one promise to resolve or rejected.
4. // Promise.race will check which promise settles (resolves or
rejects) first.
5. // If the first settled promise resolves, its value will be
passed to the .then block.
6. // If the first settled promise rejects, its reason will be
passed to the .catch block.
7.
8. let promise1 = new Promise((resolve, reject) =>
setTimeout(resolve, 500, "first")); // Resolves after 500ms
9. let promise2 = new Promise((resolve, reject) =>
setTimeout(reject, 100, "second")); // Rejects after 100ms
10.
11. Promise.race([promise1, promise2])
12. .then((value) => {
13. console.log(value); // Output: "second" (if
promise2 settles first)
14. })
15. .catch((error) => {
16. console.log(error); // Output: "second" (if
promise2 settles first and is rejected)
17. });
18.
All Promise table
o Promise.all(): Fulfills only if all promises succeed. Useful for tasks that are
dependent on the success of multiple promises.
o Promise.race(): Returns the first settled promise, whether it's fulfilled or
rejected. Useful when the timing matters and you only care about the fastest
result.
o Promise.allSettled(): Always resolves with an array of results after all
promises settle. Useful for tasks where you need the result of every promise,
including failures.
o Promise.any(): Resolves as soon as any promise fulfills. Only rejects if all
promises fail. Useful for finding the first successful result out of multiple
attempts.
Resolves
Promise Method Behavior Rejects When Use Case
When
Promise.all() Waits for all All Any single When you
promises to either promises promise rejects, need all
resolve or reject. are and it stops promises to
If all promises fulfilled. immediately. complete
resolve, it returns successfully,
Resolves
Promise Method Behavior Rejects When Use Case
When
like loading
an array of results. multiple
resources.
The first When you
Resolves or promise care only
rejects as soon as resolves. about the
The first promise
Promise.race() the first promise fastest
rejects.
settles (whether promise,
resolve or reject). regardless of
the result.
When you
After all
Waits for all need the
promises
promises to settle outcome of
have Never rejects,
(resolve or reject), every
Promise.allSettled() and returns an
settled returns results for
promise,
(either both fulfilled and
array of results whether they
resolved rejected promises.
detailing each succeed or
or
outcome. fail (error
rejected).
handling).
When you
Resolves as soon
need at least
as any one
Only if all one
promise resolves. The first
promises reject successful
Promise.any() If all promises promise
with an promise, but
reject, it returns resolves.
AggregateError. don't care
an
about
AggregateError.
rejections.
The await keyword is used within an async function to pause the execution of the
function until a promise is resolved or rejected.
Escape
Meaning Example
Sequence
\\' Single quote 'It\\'s a good day' → It's a good
day
\\" Double quote "He said, \\"Hello\\"" → He said,
"Hello"
\\\\ Backslash "This is a backslash: \\\\" → This
is a backslash: \\
"Hello\\nWorld" → Output will be on two
\\n Newline (Line break)
lines
"Hello\\tWorld" → Hello World (with
\\t Tab
tab space)
Carriage return (moves
"Hello\\rWorld" → World (the cursor
\\r cursor to the start of the
goes back to the start and overwrites Hello)
line)
"ABC\\bD" → ABD (removes the character
\\b Backspace
before D)
"Hello\\fWorld" (rarely used, behaves
\\f Form feed
differently in different contexts)
"Hello\\vWorld" (rarely used, behaves
\\v Vertical tab
differently depending on context)
o Hoisting ?
y = 10;
console.log(y);
let y;
showX(); // Output: 10
o Block Scope
Variables declared with let and const are block-scoped. This means
they are confined to the block {} in which they are declared, such as
within if, for, or other code blocks.
Block scope prevents variables from being accessed outside of the
block they are declared in, unlike var, which is not block-scoped.
Scope chain ?
Scope chaining in JavaScript refers to the process where the JavaScript engine looks
for variables starting from the current scope and then moves up through parent scopes
until it either finds the variable or reaches the global scope. If the variable is not found
in any scope along the chain, it throws a ReferenceError.
scope chain only works upward, meaning it looks for variables in the current scope
and then continues to the parent scopes
o Current Scope: The innermost block or function where the code is executing.
o Outer Scope: The immediate parent scope of the current scope.
o Global Scope: The outermost scope, where global variables and functions
reside.
Lexical Environment ?
When JavaScript code is executed, each function or block creates a new lexical
environment that keeps track of the variables declared within it. If a variable is not
found in the current environment, JavaScript looks at the outer lexical environment
(the scope where the function or block was defined) and continues until it either finds
the variable or reaches the global environment. variables are only looked up in their
parent lexical environment, not in the child environment.
function displayName() {
console.log(name);
}
displayName();
Side effects are one of the main reasons jQuery is so powerful—it allows developers
to easily create interactive and dynamic web pages. However, it’s important to
manage these side effects carefully to avoid unintended consequences in your
application.
o Side effects in jQuery occur when any interaction with elements (through
methods like .css(), .html(), .text(), .attr(), etc.) causes changes in the
DOM structure, CSS styles, or attributes.
o They are the result of manipulating elements, triggering animations, or
altering content dynamically.
Closure ?
A closure in JavaScript is a feature where an inner function has access to the outer
function's variables, even after the outer function has returned.
They are widely used for data encapsulation, event handling, and stateful
functions in JavaScript.
This Keyword ?
“this” keyword refers to the element that the event handler is attached to.
o Event object ?
This event object contains useful information about the event that occurred,
such as the type of event, the element that triggered it, and other related
details.
document.getElementById("myButton").addEventListener("click",
function(event) {
// 'event' is automatically passed as an argument
console.log("Event type:", event.type); // Output: "click"
console.log("Clicked element:", event.target); // Output:
<button id="myButton">
});
Event Listeners ?
Event listeners in JavaScript are used to detect and respond to user interactions or
browser actions. They allow you to run a specific function when an event, such as a
click, keypress, or form submission, occurs on an element.
document.getElementById('myButton').addEventListener('click',
function() {
alert('Button was clicked!');
});
o Mouse Events:
click: Triggered when an element is clicked.
dblclick: Triggered when an element is double-clicked.
mouseenter: Triggered when the mouse enters an element.
mouseleave: Triggered when the mouse leaves an element.
o Keyboard Events:
keydown: Triggered when a key is pressed.
keyup: Triggered when a key is released.
keypress: Triggered when a key is pressed down (but is now largely
deprecated in favor of keydown).
o Form Events:
submit: Triggered when a form is submitted.
change: Triggered when the value of an input field changes.
focus: Triggered when an element gains focus (like clicking into an
input field).
blur: Triggered when an element loses focus.
o Window Events:
scroll: Triggered when the user scrolls the page.
resize: Triggered when the browser window is resized.
load: Triggered when the page has fully loaded.
Event Bubbling and Capturing ?
Event Propagation:
When an event happens on an element (like clicking a button inside a div), it doesn’t
just trigger on that element, but it also propagates through its parent elements. This
process of event propagation happens in two phases:
o Event Bubbling
In event bubbling, the event starts from the target element (where the
event is triggered) and propagates upward to the parent elements in
the DOM.
This means the innermost element's event handler runs first, then its
parent's event handler, and so on, until it reaches the document or
window element.
o <div id="parent">
o <button id="child">Click Me</button>
o </div>
o
o <script>
o
document.getElementById("parent").addEventListener("click", ()
=> {
o console.log("Parent clicked");
o });
o
o
document.getElementById("child").addEventListener("click", ()
=> {
o console.log("Button clicked");
o });
o
o </script>
o Event Capturing (Trickling)
In event capturing, the event starts from the outermost parent
element and travels down to the target element.
By default, capturing is less commonly used, but you can manually
enable it in JavaScript event listeners.
o <div id="parent">
o <button id="child">Click Me</button>
o </div>
o
o <script>
o
document.getElementById("parent").addEventListener("click", ()
=> {
o console.log("Parent clicked");
o }, true); // `true` enables event capturing
o
o
document.getElementById("child").addEventListener("click", ()
=> {
o console.log("Button clicked");
o });
o
o </script>
Event Delegation ?
o Less Code: You don’t need to write multiple event listeners for each child
element.
o Dynamic Content: It works for elements that are added later (dynamically).
o Better Performance: Fewer event listeners mean less memory and better
performance.
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
// Set a click event listener on the parent <ul>
document.getElementById("myList").addEventListener("click",
function(event) {
// Check if the clicked element is an <li>
if (event.target.tagName === "LI") {
alert("You clicked on " + event.target.textContent);
}
});
</script>
Browser API ?
APIs (Application Programming Interfaces) are essential tools for web developers to
communicate between different software components.
o DOM API
getElementById(), querySelector()…………….
o XMLHttpRequeat
o Fetch API
o Storage API
localStorage, sessionStorage
o History API
pushState(), replaceState()…………………
Web storage ?
The web storage is used to store data locally with in the browser.
o Local storage
Cookies ?
Cookies are small pieces of data that are stores in the users web browser.
ES6 ?
ES6 features (like map, filter, reduce, spread, rest, ternary, optional chaining,
callback, promise, async-await).
Memoization is a technique used to make functions run faster by storing the results
of expensive function calls. If the same inputs are given again, the function returns
the cached result instead of recalculating it.
return function(n) {
if (cache[n]) return cache[n]; // Return cached result if
available
if (n <= 1) return n;
What is Recursion?
Code:
function factorial(n) {
if (n === 0) return 1; // Base case: 0! = 1
return n * factorial(n - 1); // Recursive case
}
1. factorial(5)=5×factorial(4)factorial(5) = 5 \times
factorial(4)factorial(5)=5×factorial(4)
2. factorial(4)=4×factorial(3)factorial(4) = 4 \times
factorial(3)factorial(4)=4×factorial(3)
3. factorial(3)=3×factorial(2)factorial(3) = 3 \times
factorial(2)factorial(3)=3×factorial(2)
4. factorial(2)=2×factorial(1)factorial(2) = 2 \times
factorial(1)factorial(2)=2×factorial(1)
5. factorial(1)=1×factorial(0)factorial(1) = 1 \times
factorial(0)factorial(1)=1×factorial(0)
6. factorial(0)=1factorial(0) = 1factorial(0)=1 (Base case reached)
7. Results propagate back: 1→2→6→24→120.
o Types of Recursion:
1. Direct Recursion: A function directly calls itself.
2. Indirect Recursion: A function calls another function, which in turn
calls the original function.
function even(n) {
if (n === 0) return true;
return odd(n - 1); // Calls odd
}
function odd(n) {
if (n === 0) return false;
return even(n - 1); // Calls even
}
console.log(even(4)); // true
console.log(odd(5)); // true
Tree traversal
Factorials
Fibonacci series
Searching or sorting algorithms (like quicksort, mergesort)
o Advantages:
Simplifies code for problems that are naturally recursive.
Makes code cleaner and easier to understand for divide-and-conquer
problems.
o Disadvantages:
Can be less efficient due to repeated calculations and stack overhead.
May cause a stack overflow error if the recursion depth is too large
and the base case isn't reached.
Thread vs Process
Process:
Thread:
let person = {
name: "Alice"
}
console.log(proxy.name);
Boxing
Boxing refers to the process of converting a primitive type (like a number or string)
into an object type. For example, when you try to use a method on a primitive type
(like calling .toUpperCase() on a string), JavaScript automatically "boxes" that
primitive into an object temporarily to access the method.
Array.from()
o Array.from() creates a new array from an array-like or iterable object.
o You can use it to transform a Set, Map, string, or array-like objects into a
proper array.
o It also allows for optional transformations on each element using a mapping
function.
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // Output: ['h', 'e', 'l', 'l', 'o']
Unary, Binary, and Ternary Function
1. Unary Function
2. Binary Function
3. Ternary Function
What is Throttling?
Throttling ensures that a function is called at most once every specified time interval,
no matter how many times an event occurs.
What is Debouncing?
Debouncing delays the function execution until a specific amount of time has passed
since the last event. If the event happens again before the time ends, the timer resets.
o Example: When typing in a search box, the search function executes only after
the user stops typing for, say, 300 milliseconds.
Key Differences:
Simple Analogy:
Polyfills
A polyfill is a piece of code that adds support for modern features in older browsers
or environments where those features are not natively available.
A Null Pointer Exception happens when you try to access or use an object that is
null (or undefined), meaning it doesn't exist.
Example:
let obj = null;
console.log(obj.someProperty); // Throws an error
Polling and queueing phase in event loop
1. Queueing Phase:
This deals with microtasks like promises and process.nextTick().
These tasks are executed right after the current operation finishes and
before moving to the next event loop phase.
2. Polling Phase:
This handles I/O events, like reading files or handling network
requests.
If no I/O events are ready, it waits for them or moves to the next phase.
In simple terms:
The call stack in JavaScript is a mechanism that keeps track of function calls in the
order they need to be executed. It works on the LIFO (Last In, First Out) principle,
meaning the last function added is the first to be executed.
Heap
The heap is a part of memory where objects and arrays are stored in JavaScript,
allowing the program to manage complex data. It holds data that can grow in size or
change, and the call stack keeps a reference to that data.
1. Try-Catch Block
2. Throwing Exceptions
3. Finally Block
Symbol()
A symbol in JavaScript is a special data type used to create unique keys for objects.
It ensures no two symbols are the same, even if they have the same description.
Key Points: