0% found this document useful (0 votes)
22 views

javascript theory

JavaScript is a high-level programming language used for creating dynamic web pages through DOM manipulation and event handling. It features both client-side and server-side components, supports static and dynamic typing, and has various data types and operators. The document also covers functions, loops, condition statements, and key concepts like type coercion and first-class functions.

Uploaded by

wub0fuhubis3
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

javascript theory

JavaScript is a high-level programming language used for creating dynamic web pages through DOM manipulation and event handling. It features both client-side and server-side components, supports static and dynamic typing, and has various data types and operators. The document also covers functions, loops, condition statements, and key concepts like type coercion and first-class functions.

Uploaded by

wub0fuhubis3
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

 What is JavaScript?

JavaScript is a versatile, high-level programming language. It allows developers to


create dynamic and interactive web pages by manipulating the Document Object
Model (DOM), handling events, performing calculations, validating forms, and much
more.

 Java Script Engine ?

A Java Script engine is a program that present in web browsers that exicutes
JavaScript code.

 What are client side and server side ?


o Client side

A client is a device, application,or software component that requests and


consumers services or resources from a server.

o Server side

A server is a device, computer,or software application that provides services,


resources, or functions to clients.

 Statically vs dynamically typed language ?

Statically Typed Languages

o Type Checking: Performed at compile time.


o Explicit Declaration: Variables must be declared with a specific type before
use.
o Errors: Type-related errors are caught during compilation, before the code is
run.
o Performance: Typically faster because types are known at compile time,
allowing for optimizations.
o Examples: C, C++, Java, Swift, TypeScript.

Dynamically Typed Languages

o Type Checking: Performed at runtime.


o Implicit Declaration: Variables can hold any type, and their type can change
over time.
o Errors: Type-related errors may only surface while the program is running.
o Performance: Often slower since types are resolved during execution.
o Examples: JavaScript, Python, Ruby, PHP.
 Primitive & Non-primitive data types ?
o Primitive Data Types
 Primitive data types can hold only single value
 Immutable, meaning their values, once assigned , cannot be changed.
 Fixed size: They occupy a specific amount of memory.
 Examples
 Number: Represents numeric values (42, 3.14).
 String: Represents textual data ('hello', "world").
 Boolean: Represents logical values (true, false).
 null: Represents an intentional absence of value.
 undefined: Represents a variable that has been declared but
not assigned a value.
 Symbol: Represents unique, immutable values (introduced in
ES6).
 BigInt: Used for numbers larger than what Number can
represent (introduced in ES2020).
o Non-Primitive Data Types
 Non- primitive data type can hold multiple values.
 They are mutable and their values can be changed.
 Stored by reference: They don’t store the actual value directly but
hold a reference to where the data is stored in memory
 Examples
 Object: General collection of key-value pairs.
 Array: Indexed collection of elements.
 Function: Callable objects.
 Date, RegExp, Error: Special built-in objects.
 Template Literals & String Interpolation ?

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 ${}.

let age = 25; let greeting = I am ${age} years old.;


console.log(greeting); // Outputs: I am 25 years old.

 Operators ?

Operators are symbols or keyword that perform operations on operands.

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

+ : Concatenation (joins two strings)

 Type of operator ?

Typeof operator is used to determine the type of each variable.

let num = 42;


console.log(typeof num); // "number"

**Use :**Type of operator can be used to validate the data received from external
sources(api)

 Type Coercion (Type casting)?

Type coercion is the automatic conversion of values from one data type to another
during certain operations or comparisons.

o Implicit Coercion:

Implicit Coercion: Happens automatically by JavaScript when it tries to


perform operations with values of different types.

 Implicit String Coercion:

This occurs when JavaScript automatically converts a non-string value


into a string, often when using the + operator.

let num = 10; let str = 'The number is ' + num; // 'The
number is 10'

 Implicit Boolean Coercion:

Happens when JavaScript expects a boolean value (e.g., in conditions


like if statements). It automatically converts values to true or false.
if (0) { console.log('This will not run'); // 0 is
falsy }

if ('hello') { console.log('This will run'); // Non-empty


strings are truthy }

o Explicit Coercion:

Explicit Coercion: Happens when you manually convert a value from one
type to another using built-in functions or operators.

 Explicit String Coercion:

You can explicitly convert values to strings using the String()


function or .toString() method.

let num = 123; let bool = true;

let str1 = String(num); // '123' let str2 =


num.toString(); // '123'

let str3 = String(bool); // 'true'

 Explicit Boolean Coercion:

You can explicitly convert a value to a boolean using the Boolean()


function or double negation (!!).

let value1 = 0; let value2 = 'Hello';

console.log(Boolean(value1)); // false (0 is falsy)


console.log(Boolean(value2)); // true (non-empty string
is truthy)

console.log(!!value1); // false (explicit coercion using


double negation) console.log(!!value2); // true (explicit
coercion using double negation)

 Conditions statements ?
o if Statement

if (condition) { // code to be executed if condition is true }

o if...else Statement

if (condition) { // code to be executed if condition is true } else { // code to be


executed if condition is false }

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

condition ? exprIfTrue : exprIfFalse;

let age = 18;


let result = (age >= 18) ? "You are an adult." : "You are a
minor.";
console.log(result);

 Selectors in JS?

Selectors in JS helps to get specific element from DOM based on by ID names, class
names, tag names.

let element = document.getElementById("myId");

o getElementById("id") → Selects an element by its ID.


o getElementsByClassName("class") → Selects all elements with the
specified class.
o getElementsByTagName("tag") → Selects all elements with the specified
tag.
o querySelector("cssSelector") → Selects the first element matching the
CSS selector.
o querySelectorAll("cssSelector") → Selects all elements matching the
CSS selector.
 Different types of Loops ?

Loops allow you to execute a block of code repeatedly until a specified condition is
met.

o for : Use when you know how many times to iterate.


o for (let i = 1; i <= 5; i++) {
o console.log(i); // Prints the current value of i
o }
o
o while : Use when you want to loop as long as a condition remains true.
o let a = 1;
o while(a <= 10) {
o console.log(a)
o a++;
o }
o do while : Use when you want to loop as long as a condition remains true.
o let a = 1;
o do {
o console.log(a);
o } while(a > 1)
o for in : Used to loop through the properties of an object.

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

for (key in person) {


console.log(key + " : " + person[key])
}

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

const mixedarr = [1, "string", "number", 6, 0];


for (value of mixedarr) {
console.log(value);
}

 Break and Continue Statements ?


o break: Exits the loop entirely.
o continue: Skips the current iteration and moves to the next one.
 Loops - difference between while and do-while ?

Feature while Loop do-while Loop


Condition
At the start of the loop. At the end of the loop.
Check
May not execute if the condition Always executes at least once, even
Execution
is false initially. if the condition is false initially.
Use when the loop should only run Use when you want the loop to run
Use Case if the condition is true from the at least once, regardless of the
start. condition.

 Difference between for...of and for...in ?


o for...in is for keys or indices (best for objects).
o for...of is for values (best for arrays, strings, and other iterable objects).
Feature for...in for...of
Iterates Keys (object properties, indices) Values of an iterable
Use With Objects, arrays Arrays, strings, Maps, Sets
Output Keys or indices Values
Best For Objects, array indices Arrays, strings, iterables

 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

Definition: A named function is a function that is declared with a specific


name. This can make it easier to identify and call the function later in the
code.

function sayHello() {
console.log("Hello!");
}

sayHello(); // Output: Hello!

o Function Expression

A function can also be defined as an expression and assigned to a variable.

const greet = function(name) {


console.log("Hello, " + name);
};
greet("Bob"); // Output: Hello, Bob

o Anonymous Function

These are functions without a name, often used as arguments to other


functions or immediately invoked.

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.

const greet = (name) => {


console.log("Hello, " + name);
};
greet("Charlie"); // Output: Hello, Charlie

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 greet(name, callback) {


console.log("Hello, " + name);
callback(); // The callback function is executed after
greeting.
}

function sayGoodbye() {
console.log("Goodbye!");
}

greet("Alice", sayGoodbye); // Output: Hello, Alice


// 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

First-Class Functions allow for flexible programming patterns, enabling


powerful constructs like higher-order functions and callbacks.

 Be assigned to variables.

const greet = function(name) { return Hello, ${name}; };

console.log(greet('Alice')); // Output: Hello, Alice

 Be passed as arguments to other functions.

function callFunction(fn, value) { return fn(value); }

function sayHi(name) { return Hi, ${name}; }


console.log(callFunction(sayHi, 'Bob')); // Output: Hi,
Bob

 Be returned from other functions.


 function createGreeting(greeting) {
 return function(name) {
 return ${greeting}, ${name}!;
 };
 }`

 `const greetHello = createGreeting('Hello');
 console.log(greetHello('Alice')); // Output: Hello,
Alice!
o IIFE (Immediately Invoked Function Expression) ?

An IIFE (Immediately Invoked Function Expression) is a JavaScript


function that runs as soon as it is defined.

(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

 Math.ceil(): Rounds a number up to the next largest integer.

console.log(Math.ceil(4.1)); // Output: 5
console.log(Math.ceil(4.9)); // Output: 5

 Math.floor(): Rounds a number down to the largest integer less than


or equal to the number.

console.log(Math.floor(4.9)); // Output: 4
console.log(Math.floor(4.1)); // Output: 4

 Math.max(): Returns the largest of zero or more numbers.

console.log(Math.max(1, 3, 2)); // Output: 3


console.log(Math.max(-1, -5, 0)); // Output: 0

 Math.min(): Returns the smallest of zero or more numbers.

console.log(Math.min(1, 3, 2)); // Output: 1


console.log(Math.min(-1, -5, 0)); // Output: -5
 Math.random(): Generates a random number between 0 (inclusive)
and 1 (exclusive).

console.log(Math.random()); // Output: Random number


between 0 and 1

 Math.sqrt(): Returns the square root of a number.

console.log(Math.sqrt(16)); // Output: 4
console.log(Math.sqrt(25)); // Output: 5

 Math.pow(): Returns the base to the exponent power (base^exponent).

console.log(Math.pow(2, 3)); // Output: 8 (2^3)


console.log(Math.pow(5, 2)); // Output: 25 (5^2)

 Math.abs(): Returns the absolute value of a number.

console.log(Math.abs(-5)); // Output: 5
console.log(Math.abs(3)); // Output: 3

 Math.PI: Returns the value of π (Pi), approximately 3.14159.

console.log(Math.PI); // Output: 3.141592653589793

o Pure Function and Side Effect

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

console.log(add(2, 3)); // Output: 5


console.log(add(2, 3)); // Output: 5 (same input, same output)
Pure Function Function with Side Effects
Always returns the same output for the Output can change based on external
same input factors
Does not change anything outside the
May modify external variables or data
function
Harder to test because of external
Easy to test and understand
dependencies
Keeps data unchanged (immutability) May change data or state (mutability)

o Impure Function

An impure function is a function that may cause side effects or return


different outputs for the same inputs.
let count = 0;

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)

 An impure function can modify things outside its own scope or


depend on factors beyond the given inputs.
 It is common in real-world applications where external interaction,
such as modifying the UI or making network requests, is necessary.
o generator Function

A generator function in JavaScript is a special type of function that allows


you to pause and resume execution, which is useful for managing
asynchronous tasks, creating iterators, and handling complex data flows.

 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

A factory function is a function in JavaScript (or other languages) that returns


an object without using the new keyword, which is typically used with
constructor functions or classes.

function createPerson(name, age) {


return {
name: name,
age: age,
greet() {
console.log("Hello, my name is " + this.name);
}
};
}

const person1 = createPerson("Alice", 30);


const person2 = createPerson("Bob", 25);

person1.greet(); // "Hello, my name is Alice"


person2.greet(); // "Hello, my name is Bob"

o eval() Function

it is a built in function that evaluates a string as a JavaScript code and


dynamically executes it.

let result = eval('2 + 2'); console.log(result); // Output: 4

 Currying ?

Currying transform a function with multiple arguments into a nested series of


function, each taking a single argument.

// A regular function that takes 3 arguments


function addThreeNumbers(a, b, c) {
return a + b + c;
}

console.log(addThreeNumbers(1, 2, 3)); // Outputs: 6

// Curried version of the above function


function curriedAdd(a) {
return function(b) {
return function(c) {
return a + b + c;
};
};
}

// Using the curried function


console.log(curriedAdd(1)(2)(3)); // Outputs: 6

Why Use Currying:

1. Reusability: Lets you reuse a function with some fixed values.


2. Partial Application: Pre-sets some values and applies the rest later.
3. Cleaner Code: Breaks complex tasks into smaller parts.
4. Functional Programming: Helps in building functions that work well
together.

When to Use Currying:

5.When some function parameters stay the same.


6.When you need a more specific version of a function.
7.When you want simpler, reusable functions.
 Arguments & Parameter ?
o Arguments

Arguments are the actual values or expressions passed to the function when it
is called.

add(5, 10); // 5 and 10 are arguments

o Parameters

Parameters are placeholders that are defined in the function declaration.

function add(a, b) { // 'a' and 'b' are parameters return a +


b; }

 Default Parameter ?

Default parameters allow you to specify default values for function parameter.

function greet(name = 'Guest') { console.log(Hello, ${name}!); }

 Call, apply, and bind ?

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.

let fruits = ["apple", "banana", "cherry"];

Using the Array constructor:

let numbers = new Array(1, 2, 3, 4);

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"]

1- start index and 3- end intex, end intex not included.

 find() : Methord get first element that satisfies a condition.


 let numbers = [5, 12, 8, 130, 44];

 // Find the first number greater than 10
 let found = numbers.find(function(num) {
 return num > 10;
 });
 console.log(found); // Output: 12 (the first number
greater than 10)
 indexOf() : Method returns the first index at which a specified
value can be found in the array, or -1 if it is not present.
 let fruits = ["apple", "banana", "cherry",
"banana"];
 let index = fruits.indexOf("banana");
 console.log(index); // Output: 1 (the first
occurrence)
 Add
 push(): Adds elements to the end of an array.
 let fruits = ["apple", "banana"];
 fruits.push("cherry");
 console.log(fruits); // Output: ["apple", "banana",
"cherry"]
 concat(): Combines two or more arrays.
 let arr1 = [1, 2];
 let arr2 = [3, 4];
 let combined = arr1.concat(arr2);
 console.log(combined); // Output: [1, 2, 3, 4]

create a new array but not modifying original array.

 unshift(): Adds elements to the beginning of an array.


 let fruits = ["banana", "cherry"];
 fruits.unshift("apple");
 console.log(fruits); // Output: ["apple", "banana",
"cherry"]
 Remove
 pop(): Removes the last element from an array.
 let fruits = ["apple", "banana", "cherry"];
 fruits.pop();
 console.log(fruits); // Output: ["apple", "banana"]
 shift(): Removes the first element from an array.
 let fruits = ["apple", "banana", "cherry"];
 fruits.shift();
 console.log(fruits); // Output: ["banana",
"cherry"]
 splice(): Adds/removes or replace elements from an array at
a specific index.
 let fruits = ["apple", "banana", "cherry"];
 fruits.splice(1, 1, "blueberry");
 console.log(fruits); // Output: ["apple",
"blueberry", "cherry"]

array.splice(startIndex, deleteCount, …..ItamsToAdd);

 Modify
 forEach(): Executes a function for each element in the array.

Perform some operation on each element of an array without


creating a new array.

let fruits = ["apple", "banana", "cherry"];


fruits.forEach(function(fruit) {
console.log(fruit);
});
// Output: apple, banana, cherry

without creating new array

 map(): Creates a new array with the results of calling a


function on every element.

To modify each element of an array and create a new array with


the modified values.
let numbers = [1, 2, 3, 4];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8]

 Others
 length: Returns the number of elements in an array.

let fruits = ["apple", "banana", "cherry"];


console.log(fruits.length); // Output: 3

 flat() : Flatten nested arrays, merging sub-arrays into the


main array up to a specified depth.

array.flat(depth);

const arr = [1, 2, [3, 4], 5, [6, 7]]; const


flatArray = arr.flat(); // Flattens 1 level deep
console.log(flatArray); // [1, 2, 3, 4, 5, 6, 7]

 reduce(): Reduces the array to a single value.


 let array1 = [1, 2, 3, 4, 5, 6];
 console.log(array1);//[1, 2, 3, 4, 5, 6]
 //reduce()
 let sum = array1.reduce((a, b) => (a + b));
 console.log(sum);//21
 **join() :**Joins array elements into a string, with an
optional separator.

let fruits = ["apple", "banana", "cherry"]; let


result = fruits.join(" - ");
console.log(result); // Output: "apple - banana -
cherry"

 sort() : Method sorts the elements of an array in place and


returns the sorted array.

let fruits = ["banana", "apple", "cherry"];


fruits.sort(); console.log(fruits); // Output:
["apple", "banana", "cherry"]

 some(): Checks if at least one element in an array satisfies a


condition. Returns true if any element passes, otherwise
false.

let numbers = [3, 5, 7, 8];

// Check if any number is even let hasEven =


numbers.some(function(num) { return num % 2 ===
0; }); console.log(hasEven); // Output: true (since
8 is even)

 every(): Checks if all elements in an array satisfy a condition.


Returns true if all elements pass, otherwise false.
let numbers = [2, 4, 6, 8];

// Check if all numbers are even let allEven =


numbers.every(function(num) { return num % 2 === 0;
}); console.log(allEven); // Output: true (since
all numbers are even)

 reverse(): Reverses the order of elements in an array.

let numbers = [1, 2, 3, 4, 5];

// Reverse the array numbers.reverse();


console.log(numbers); // Output: [5, 4, 3, 2, 1]

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:

function example() { console.log(arguments); }

example(1, 2, 3); // Outputs: {0: 1, 1: 2, 2: 3, length: 3}

 Array vs Set ?

Feature Array Set


Data Structure Ordered collection of elements. Collection of unique values.
Allow Yes, arrays can have duplicate No, sets do not allow duplicate
Duplicates values. values.
Access No index; iterate using
By index (arr[0], arr[1], etc.).
Elements .forEach() or .values().
Faster lookup for unique elements
Slower when searching for
Performance because of its unique value
elements, especially large arrays.
property.
push(), pop(), shift(),
Common add(), has(), delete(),
unshift(), filter(), map(),
Methods clear(), size.
reduce().
Suitable for ordered data, list- Suitable for maintaining unique
Use Cases
based operations, transformations. values, avoiding duplicates.

 JSON & JSON Methods ?

JSON is a lightweight data format used to represent structured data. It is primarily


used for transferring data between a server and a web application.
o eg :

{ "name": "John", "age": 30, "isStudent": false, "courses":


["Math", "Science"], "address": { "city": "New York",
"zipcode": "10001" } }

Common JSON Methods

o JSON.stringify(): Converts a JavaScript object into a JSON string.

Usage: When you need to send data to a server.

const person = { name: "Alice", age: 25, city: "Paris" }; const


jsonString = JSON.stringify(person);
console.log(jsonString); // Output:
'{"name":"Alice","age":25,"city":"Paris"}'

o JSON.parse(): Converts a JSON string back into a JavaScript object.

Usage: When you receive data from a server in JSON format.

const jsonString = '{"name":"Alice","age":25,"city":"Paris"}';


const person = JSON.parse(jsonString);
console.log([person.name](<http://person.name/>)); // Output:
Alice

 Array destructuring ?

Array destructuring in JavaScript is a concise way to extract values from an array


and assign them to variables.

const fruits = ["apple", "banana", "mango", "orange"];


const [firstFruit, secondFruits, thirdFruits] = fruits;

console.log(firstFruit); // Output: apple


console.log(secondFruits); // Output: ["banana", "mango", "orange"]

 Spread and rest operator ?


o Spread

The spread operator is used to "spread" elements of an iterable (like an array


or an object) into individual elements.

const arr1 = [1, 2, 3];


const arr2 = [4, 5, 6];

const combinedArray = [...arr1, ...arr2];


console.log(combinedArray); // [1, 2, 3, 4, 5, 6]

 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

The rest operator is used in function parameters to collect all remaining


arguments into an array.

function display(first, second, ...remaining) {


console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(remaining); // Output: [3, 4, 5]
}

display(1, 2, 3, 4, 5);

 Objects ?

let person = { name: "Alice", age: 30, greet: function()


{ console.log("Hello, my name is " +
[this.name](<http://this.name/>)); } };

person.greet(); // Output: "Hello, my name is Alice"

 Object methods ?
o Object.assign(): Copies properties from one or more source objects to a
target object.

const target = {}; const source = { name: "John" };


Object.assign(target, source); // target is now { name:
"John" }

o Object.keys(): Returns an array of a given object's own enumerable


property names.

const user = { name: "John", age: 25 };


console.log(Object.keys(user)); // Output: ["name", "age"]

o Object.values(): Returns an array of a given object's own enumerable


property values.
o Object.entries(): Returns an array of a given object's key-value pairs.
o Object.fromEntries(): Converts a list of key-value pairs back into an
object.
o Object.create(): Creates a new object using an existing object as the
prototype.

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.

Before short hand

let name = "Alice"; let age = 25;

const user = { name: name, age: age };

After Short hand

const user = { name, age }; // Same as { name: name, age: age }


console.log(user); // Output: { name: "Alice", age: 25 }

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

// Access nested properties without optional chaining


console.log(user.address.city); // Output: "Paris"

// Access using optional chaining


console.log(user.address?.city); // Output: "Paris"
console.log(user.contact?.email); // Output: undefined (no error even
if contact is undefined)

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

let userName = null;


let defaultName = "Guest";

// Using nullish coalescing


let name = userName ?? defaultName; // Output: "Guest"

// Using || would return "Guest" even for false, 0, '', etc.


let value = 0;
console.log(value || 5); // Output: 5 (because 0 is falsy)
console.log(value ?? 5); // Output: 0 (because 0 is not null or
undefined)

 Prototypes ?

o In JavaScript, prototypes are a fundamental feature that enable inheritance


and method sharing among objects.
o Every JavaScript object has an internal property called [[Prototype]], which
can be accessed using Object.getPrototypeOf() or the __proto__
property.
o The prototype is essentially another object from which the original object can
inherit properties and methods.
 Prototypical inheritance ?
o Prototypical inheritance is a method by which objects can inherit properties
and methods from other objects through their prototype chain.
o This allows for a flexible and efficient way to create object hierarchies without
the need for class-based inheritance.
 Set ?

A Set object is a collection of unique values, means there are no duplicate values.

let mySet = new Set();

mySet.add(1);
mySet.add(2);
mySet.add(2); // Duplicate value, will be ignored
console.log(mySet); // Outputs: Set { 1, 2 }

Method/Property What it does

add(value) Adds a value (no duplicates).


has(value) Checks if the value exists.
delete(value) Removes a value.
clear() Removes all values.
size Returns how many values there are.
forEach() Runs a function for each value.

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

// Create a new Map


const map = new Map();

// Set key-value pairs


map.set(1, 'One');
map.set(2, 'Two');

// Get a value by key


console.log(map.get(1)); // Output: "One"
console.log(map.get(2)); // Output: "Two"

let myMap = new Map();

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.

 Differences between a Map and an Object ?


Feature Map Object
Any data type (objects,
Key Types Strings or symbols
numbers, etc.)
Unordered (modern engines maintain
Key Order Ordered by insertion
order)
Key Strict (e.g., 1 and '1' are
Not strict (e.g., 1 and '1' are the same)
Uniqueness different)
size property returns the No direct property, use
Size Property
number of entries Object.keys().length

Can iterate directly with Requires Object.keys(),


Iteration Object.values(), or
for...of, forEach()
Object.entries()
Optimized for frequent Slightly slower for frequent
Performance
additions/removals modifications
Inherits default keys from
Default Keys No default keys
Object.prototype like toString
Best for collections of key- Best for simple key-value pairs with
Use Case
value pairs with any key type string keys

 weekSet & weekMap ?


o weekSet

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.

// Create a new WeakSet


let weakSet = new Set();

let obj1 = { name: "John" };


let obj2 = { name: "Jane" };

// Add objects to the WeakSet


weakSet.add(obj1);
weakSet.add(obj2);

// Check if an object is in the WeakSet


console.log(weakSet.has(obj1)); // Output: true
console.log(weakSet.has(obj2)); // Output: true

// Remove object from the WeakSet


weakSet.delete(obj1);
console.log(weakSet.has(obj1)); // Output: false

 add(value): Adds an object to the WeakSet.


 delete(value): Removes the object from the WeakSet.
 has(value): Checks if an object exists in the WeakSet.
o weekMap

A WeakMap is a collection of key-value pairs where the keys are objects


and the values can be any type. The references to the object keys are weak,
meaning if there is no other reference to the key object, it can be garbage-
collected.

// Create a new WeakMap


let weakMap = new WeakMap();

let obj1 = { name: "John" };


let obj2 = { name: "Jane" };

// Add key-value pairs to the WeakMap


weakMap.set(obj1, 'Student');
weakMap.set(obj2, 'Teacher');

// Get values using the object keys


console.log(weakMap.get(obj1)); // Output: 'Student'
console.log(weakMap.get(obj2)); // Output: 'Teacher'

// Check if a key exists


console.log(weakMap.has(obj1)); // Output: true

// Remove a key-value pair


weakMap.delete(obj2);
console.log(weakMap.has(obj2)); // Output: false

 set(key, value): Adds a key-value pair to the WeakMap.


 get(key): Retrieves the value associated with the key.
 delete(key): Removes the key-value pair from the WeakMap.
 has(key): Checks if a key exists in the WeakMap.

Feature WeakSet WeakMap


Type of Keys must be objects, values can
Only stores objects.
elements be any type.
No iteration (forEach, for..of, No iteration (forEach, for..of,
Iteration
etc. not supported). etc. not supported).
Weak references to objects, Weak references to keys,
Garbage
automatically removed when no automatically removed when no
collection
other references exist. other references exist.
Methods add(), delete(), has() set(), get(), delete(), has()
Store key-value pairs where keys
Track object existence while
Use case are objects and can be garbage-
allowing garbage collection.
collected.

 Use of Strict ?

Strict Mode makes it easier to catch common coding errors and prevents the usage
of unsafe features in JavaScript.

o Prevents Undeclared Variables:

"use strict"; x = 10; // Error: x is not defined

o Disallows Duplicates in Function Parameters:


"use strict"; function sum(a, a) { // Error: Duplicate
parameter name not allowed }

o Disables this Binding to window (Global Object):

"use strict"; function test() { console.log(this); // undefined


} test();

o Prevents Deleting Variables or Functions:

"use strict"; var x = 10; delete x; // Error: Cannot delete 'x'

 Class and constructor ?

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.

 Styling console log ?

console.log('%cYour message', 'CSS styles');

 Synchronous & Asynchronous Programing ?


o Synchronous Programming
 Synchronous programming allows multiple tasks or operations to be
initiated and executed one after the other.
 Synchronous operations block the execution of the code, meaning that
the next task cannot start until the current task is finished.
o Asynchronous Programming
 Asynchronous programing allows multiple tasks or operations to be
initiates and executed concurrently
 Asynchronous operation do not block the execution of the code.

Use :

 Fetching Data from API


 Downloading Files
 Uploading Files

Feature Synchronous Asynchronous


Execution
Sequential (one after another) Can run out of order
Order
Blocks execution until the task Non-blocking, allows other code to
Blocking
completes run
Network requests, file I/O, long
Use Cases Simple tasks, quick operations
computations
Syntax Direct function calls Callbacks, promises, async/await

 Achieving Synchronous Operation ?


o setTimeout
o setInteval
o Callbacks
o Promises
o Async/await
o Generator with yield
o Event-driven programing
 Callback Hell ?

Callback Hell refers to the scenario where multiple asynchronous operations


(callbacks) are nested inside each other. This nesting makes the code difficult to read
and maintain, often forming a “pyramid” shape.

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

 Set Timeout, Set Interval ?

Feature setTimeout() setInterval()


Executes a function once after a Repeatedly executes a function at
Execution
delay. regular intervals.
Returns a timeout ID, which can be Returns an interval ID, which can be
Returns
used to cancel the timeout. used to stop the interval.
Useful for delayed execution of a Useful for executing tasks repeatedly
Use Case
task. at set intervals.


 Promises ?

1. Promises in JS are a way to handle asynchronous operations.


2. A promise can be in one of three states: pending, resolved, or rejected.
3. A promise represents a value that may not be available yet but will be
available at some point in the future.

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 ?

Consuming a Promise means handling the result of a Promise after it resolves or


rejects. This is done using:

1. then: To handle a resolved Promise (success case).


2. catch: To handle a rejected Promise (error case).
3. finally: To execute code after the Promise settles, regardless of its outcome.
 Promises chaining ?

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

A Promise combinator is a method that helps manage multiple promises together,


allowing you to handle them in various ways. It simplifies coordinating and managing
asynchronous operations by grouping promises and defining how to handle their
resolution or rejection.

eg:

o Promise.all()
o Promise.allSettled()
o Promise.race()
o Promise.any()
 Promise.all () ?

1. Promise.all () is used to handle multiple promises concurrently


2. Promise.all () takes an array of properties as input parameter and returns a
single promise
3. Promise.all () waits for all promises to resolve or at least one promises to
reject.

Key Points About Promise.all():

4. All Promises Must Resolve:


 It waits for all promises in the array to resolve.
 If all are resolved, it returns a single promise that resolves to an array
of the resolved values.
5. Reject Behavior:
 If any one of the promises rejects, Promise.all() immediately
returns a rejected promise.
 It doesn't wait for the remaining promises to resolve or reject.
6. // Promise.all will wait for all the promises to resolve.
7. // If any promise is rejected, it will immediately go to the
catch block.
8.
9. let promise1 = Promise.resolve(2);
10. let promise2 = Promise.resolve(3);
11. let promise3 = Promise.resolve(5);
12.
13. Promise.all([promise1, promise2, promise3])
14. .then((values) => {
15. console.log(values); // Output: [2, 3, 5] if all
promises resolve successfully
16. })
17. .catch((error) => {
18. console.log(error); // Will run only if one of the
promises is rejected
19. });
 Promise.allSettled () ?

The Promise.allSettled() method in JavaScript takes an iterable of promises and


returns a single promise that resolves after all of the promises have either resolved
or rejected.

// Promise.allSettled will return the status of all promises, whether


resolved or rejected.

let promise1 = Promise.resolve(3);


let promise2 = Promise.reject("failed");
let promise3 = Promise.resolve(7);

Promise.allSettled([promise1, promise2, promise3])


.then((results) => {
console.log(results);
// Output will be an array of objects with the status and
value/reason of each promise:
// [
// { status: 'fulfilled', value: 3 },
// { status: 'rejected', reason: 'failed' },
// { status: 'fulfilled', value: 7 }
// ]
});

 Promise.any () ?

The Promise.any() method takes an iterable of promises and returns a single


promise that resolves as soon as any of the promises resolve. If all the promises
reject, Promise.any() returns a rejected promise with an AggregateError
containing all the rejection reasons.

// Promise.any will return the first resolved promise.


// If all promises are rejected, it will go to the catch block with
an AggregateError.

let promise1 = Promise.resolve();


let promise2 = Promise.reject("failed");
let promise3 = Promise.resolve(4);

Promise.any([promise1, promise2, promise3])


.then((data) => {
console.log(data); // Output: the first resolved promise
(e.g., undefined if resolved with no value)
})
.catch((error) => {
console.log(error); // Output: AggregateError if all promises
are rejected
});

First resolved: Success 2

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

 Async and Sync, await ?

The async keyword is used to define a function as an asynchronous function, which


means the code inside async function will not block the execution other code.

The await keyword is used within an async function to pause the execution of the
function until a promise is resolved or rejected.

 Null, undefined, and not defined ?


o Null

Definition: null is an intentional assignment to represent "no value" or


"empty." It is explicitly set by the developer.

let b = null; console.log(b); // Output: null

 Use null when you want to explicitly assign an empty or non-existent


value.
o Undefined
Definition: A variable is undefined if it has been declared but not assigned
any value.

let a; console.log(a); // Output: undefined

 Use undefined when something hasn't been assigned a value yet.


o Not defined

Definition: A variable is considered "not defined" if it has not been declared


in any scope (global or local).

console.log(c); // ReferenceError: c is not defined

 Handle not defined carefully to avoid reference errors, especially in


larger applications where variable declaration matters for debugging.
 Escape Sequence ?

An escape sequence in programming is a combination of characters that represents a


special character or action.

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)

 Deep Copy & Shallow Copy ?


o Deep Copy:
 Creates a completely independent copy, including all nested objects.
 Changes to the copied object do not affect the original object.
o let original = { name: "Alice", address: { city: "New
York" } };
o
o // Deep copy using JSON.stringify and JSON.parse
o let deepCopy = JSON.parse(JSON.stringify(original));
o
o // Changing the city in the deep copy
o deepCopy.address.city = "Los Angeles";
o
o // Only the deep copy is affected, original stays the same
o console.log(original.address.city); // Outputs: New York
o console.log(deepCopy.address.city); // Outputs: Los Angeles
o Shallow Copy:
 Copies only the top-level properties of an object or array.
 If the object contains nested objects, it only copies their references,
not the objects themselves.
 Changes to nested objects in the copied object affect the original
object.
o let original = { name: "Alice", address: { city: "New
York" } };
o
o // Shallow copy using spread operator
o let shallowCopy = { ...original };
o
o // Changing the city in the shallow copy
o shallowCopy.address.city = "Los Angeles";
o
o // Both original and shallow copy are affected
o console.log(original.address.city); // Outputs: Los Angeles
o console.log(shallowCopy.address.city); // Outputs: Los Angeles
 Dom ?

The DOM (Document Object Model) is a programming interface for web


documents. It represents the structure of a webpage as a tree of objects, allowing
developers to interact with and manipulate the content, structure, and style of HTML
documents using programming languages like JavaScript.

o Hoisting ?

hoisting in JavaScript means that variable and function declarations are


moved to the top of their scope (the area of the code where they exist) before
the code runs.

console.log(y); // ReferenceError: Cannot access 'y' before


initialization
let y = 10;

y = 10;
console.log(y);
let y;

 Inner HTML & textContent ?


o innerHTML: Used for setting or getting HTML content, including tags and
elements.
o textContent: Used for setting or getting plain text without interpreting
HTML.
 Scope (Global, Local, Block, Function) ?

Scope determines the visibility and lifetime of variables and functions.


It helps avoid naming conflicts, as variables with the same name can exist in
different scopes without interfering with each other.

o Global Scope ****


 Variables declared outside of any function or block are in the global
scope.
 They can be accessed and modified anywhere in the code.
 In a browser, global variables are added as properties of the window
object.

var x = 10; // Global variable

function showX() { console.log(x); // Can access global


variable }

showX(); // Output: 10

o Local ( Function ) Scope


 Variables declared inside a function are in local scope, meaning they
are only accessible within that function.
 Variables declared with var have function scope, meaning they are
confined to the function in which they are declared.

function myFunction() { var y = 20; // Local variable


console.log(y); // Output: 20 }

myFunction(); console.log(y); // Error: y is not defined

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.

if (true) { let z = 30; // Block-scoped variable


console.log(z); // Output: 30 }

console.log(z); // Error: z is not defined

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

let name = "Messi";

function displayName() {
console.log(name);
}

displayName();

o When displayName() is invoked, a new execution context is created.


o Inside this execution context, the function looks for name:
 It first looks in its own local scope (inside the function) but doesn't
find name.
 It then looks in the outer (global) scope and finds name = "Messi".
o The function successfully prints "Messi" to the console.
 jQuery Side Effects ?

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.

 Passed By Value vs Passed By Reference ?

Feature Passed by Value Passed by Reference


Primitive types (numbers, strings, Objects (arrays, functions,
Data Types
booleans, etc.) objects, etc.)
Feature Passed by Value Passed by Reference
A reference to the original
Behavior A copy of the value is passed
object is passed
Changes inside
Do not affect the original variable Affect the original object
Function
let obj = {a: 1};
Example let x = 5; modify(x);
modify(obj);

 JavaScript coding conventions ?

Following JavaScript coding conventions helps maintain clean, readable, and


maintainable code. These guidelines cover aspects like naming conventions,
indentation, comments, and best practices for writing efficient and error-free code.

 This Keyword ?

“this” keyword refers to the element that the event handler is attached to.

o Global Context: this refers to the global object (window in browsers).


o Function Context: this refers to the global object (or undefined in strict
mode).
o Object Method: this refers to the object the method belongs to.
o Constructor Function: this refers to the newly created object.
o Arrow Functions: this is inherited from the surrounding lexical
environment.
o Event Handlers: this refers to the DOM element that triggered the event.
 Event & Event Object ?

An event refers to an action or occurrence recognized by the browser, such as a user


interaction or the browser itself doing something (like loading a page).

o Event object ?

Whenever an event is triggered, the browser automatically create an event


object and passes it as an argument to the event handler function.

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 ?

Event Delegation is a technique in JavaScript where you attach an event listener to a


parent element, and that one listener can handle events for all of its child elements.
This works because events on child elements "bubble up" to their parents.

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

open(), snd(), setReqestHeader()……………………..

o Fetch API

fetch(), then(), json()………….

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

It is a web storage feature provided by web browsers that allows web


applications to store key-values pairs of data locally on the users device.

1. Storing user preferences or settings. Theme (dark/ light), language


(English, Hindi)
2. Caching data to improve performance
3. Remembering User Action and State
4. Implementing offline functionality
5. Storing client-side tokens
Feature Local Storage Session Storage
Stays even after closing the Cleared when the tab or window is
Data Lifespan
browser. closed.
Shared across all tabs and Only available in the specific
Scope
windows. tab/window.
Storage
Around 5-10 MB. Around 5 MB.
Capacity
Store long-term data (e.g., user Store temporary data (e.g., form
Use Case
settings). data).

 Cookies ?

Cookies are small pieces of data that are stores in the users web browser.

Feature Cookies Local Storage Session Storage


Can be set to expire, or Deleted when the
Data Persists until manually
deleted when browser is tab/window is
Lifespan deleted.
closed. closed.
Size Limit 4 KB per cookie. Around 5-10 MB. Around 5 MB.
Sent to Yes, with every HTTP No, only accessible via No, only accessible
Server request. JavaScript. via JavaScript.
Vulnerable to XSS No direct security issues
Security Similar to Local
attacks if not properly but still accessible via
Concerns Storage.
secured. JavaScript.

 ES6 ?

ECMAScript(ES6) is the standard JavaScript.

ES6 features (like map, filter, reduce, spread, rest, ternary, optional chaining,
callback, promise, async-await).

 What is Memoization in JavaScript ?

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.

o Memoization saves the result of a function when it's first calculated.


o The next time you call the function with the same input, it just returns the
stored result (the cached result), saving time.
o Example
o function fibonacci(n) {
o if (n <= 1) return n;
o return fibonacci(n - 1) + fibonacci(n - 2);
o }
o
o console.log(fibonacci(5)); // Slow due to repeated calculations
o

With Memoization (Fast):


nction memoizedFibonacci() {
const cache = {}; // Cache to store results

return function(n) {
if (cache[n]) return cache[n]; // Return cached result if
available
if (n <= 1) return n;

const result = memoizedFibonacci()(n - 1) +


memoizedFibonacci()(n - 2);
cache[n] = result; // Store the result in the cache
return result;
};
}

const fibonacci = memoizedFibonacci();


console.log(fibonacci(5)); // Fast because of caching

 What is Recursion?

Recursion is a programming concept where a function calls itself directly or


indirectly to solve a smaller instance of the same problem. It continues this process
until it reaches a stopping condition, called the base case, which prevents infinte calls.

o Key Characteristics of Recursion:


1. Base Case: The condition where the recursion stops.
2. Recursive Case: The part where the function calls itself with a smaller
or simpler input.
3. Call Stack: Each recursive call is added to the call stack, and
execution resumes from the last call once the base case is reached.
o Example of Recursion (Factorial Function):

The factorial of a number nnn is defined as n!=n×(n−1)×(n−2)…1n! = n \times


(n-1) \times (n-2) \dots 1n!=n×(n−1)×(n−2)…1.

Code:

function factorial(n) {
if (n === 0) return 1; // Base case: 0! = 1
return n * factorial(n - 1); // Recursive case
}

console.log(factorial(5)); // Output: 120

How It Works (Step-by-Step):


For factorial(5):

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.

1→2→6→24→1201 \rightarrow 2 \rightarrow 6 \rightarrow 24 \


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

Example of Indirect Recursion:

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

o When to Use Recursion:

Problems that can be broken into smaller subproblems, such as:

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

o A process is like a program that is running on your computer.


o Each process works by itself, with its own memory and resources.
o For example, when you open an app like Chrome, each tab is a separate
process.

Thread:

o A thread is a small task that runs inside a process.


o A process can have multiple threads, and these threads share the same
memory.
o Think of a thread as a worker doing a job for a process. For example, a process
might have threads for downloading data, showing images, or running code.
 Proxy Object

Proxy is used to manipulate or control how an object behaves.

let person = {
name: "Alice"
}

let proxy = new Proxy(person, {


get: (target, prop) => "Hello " + target[prop]
});

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.

let str = "hello";

// JavaScript automatically boxes the primitive string into a String


object
console.log(str.toUpperCase()); // +HELLO

let num = 5; // primitive number


let numObj = new Number(5); // boxed number object

 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

o Definition: A function that takes exactly one argument.


o Purpose: Performs an operation on a single input.
o Example:
o const square = (x) => x * x;
o console.log(square(5)); // Output: 25

2. Binary Function

o Definition: A function that takes exactly two arguments.


o Purpose: Performs an operation involving two inputs.
o Example:
o const add = (a, b) => a + b;
o console.log(add(5, 3)); // Output: 8

3. Ternary Function

o Definition: A function that takes exactly three arguments.


o Purpose: Performs an operation involving three inputs.
o Example:
o const sumThree = (a, b, c) => a + b + c;
o console.log(sumThree(1, 2, 3)); // Output: 6
 Memory Management

Memory management refers to the process of allocating, using, and releasing


computer memory in a program to optimize performance and prevent memory leaks.

 Throttling and Debouncing

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.

o Example: If a user scrolls continuously, the throttled function will execute,


say, every 200 milliseconds, even if the event fires more frequently.

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:

Feature Throttling Debouncing


Limits the number of times a Delays the function until after a
Purpose
function runs within a period. period of inactivity.
Executes at regular intervals (e.g., Executes only once after the events
Execution
every 200ms). stop.
Scrolling, resizing windows
Search boxes, auto-save (actions
Use Case (frequent actions requiring periodic
requiring response after a user stops).
updates).

Simple Analogy:

o Throttling: Think of a leaky faucet dripping water at fixed intervals (no


matter how much you turn it).
o Debouncing: Think of waiting to hear someone’s footsteps; if they keep
moving, you wait until they stop.
o Example: When typing in a search box, the search function executes only after
the user stops typing for, say, 300 milliseconds.
 Idempotency

Idempotency is a property of an operation where performing it multiple times


produces the same result as performing it once. In other words, no matter how many
times you repeat the operation, the outcome will remain unchanged after the first
successful execution.

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

 Null Pointer Exception

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:

o Queueing: Handles tasks like promises and nextTick right away.


o Polling: Waits for and handles I/O tasks like file reads or network requests.
 call stack

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.

 Call Stack and Heap


o Call Stack:
 Handles the execution of code.
 Stores primitive values directly and references to objects in the heap.
o Heap:
 Used for storing complex, non-primitive data (e.g., objects, arrays,
closures).
 Objects in the heap are not removed when a function finishes
executing, as long as a reference exists.
o Interaction:
 When a function executes, the call stack allocates memory for local
variables.
 If the variable is a primitive, it stays in the stack.
 If the variable is an object, its reference is stored in the stack, and the
actual object is stored in the heap.
o Garbage Collection:
 If no references to a heap object remain in the stack (or elsewhere), it
gets removed during garbage collection.
 function createUser() {
 let name = "Alice"; // Primitive stored in the stack
 let user = { age: 25 }; // Object stored in the heap, reference in
the stack
 console.log(name); // Access primitive from stack
 console.log(user.age); // Access object property from heap via
reference
 }

 createUser();
o The call stack is temporary and handles execution.
o The heap is for long-term data storage, managed by references.
o JavaScript's garbage collector automatically cleans up unused heap data.
 Microtasks vs Macrotasks

Category Microtasks Macrotasks


Higher priority, run before
Priority Lower priority, run after microtasks
macrotasks
Promises, async/await,
setTimeout(), setInterval(),
queueMicrotask(),
Examples requestAnimationFrame(),
process.nextTick()
setImmediate() (Node.js), I/O events
(Node.js)
Execution After the current script After microtasks, in the next event loop
Order execution, before macrotasks iteration

 Exception Handling in JavaScript

Exception handling is the process of managing runtime errors in a program. In


JavaScript, exceptions are typically errors that occur during the execution of the code.
The goal of exception handling is to prevent the program from crashing by catching
errors and allowing the program to continue running or fail gracefully.

JavaScript provides several mechanisms for handling exceptions:

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.

const sym1 = Symbol('id');


const sym2 = Symbol('id');

console.log(sym1 === sym2); // false (Each symbol is unique)

const obj = {};


obj[sym1] = 'Hello';
console.log(obj[sym1]); // Hello

Key Points:

1. Symbols are unique: No two symbols are the same.


2. Used as object keys: Useful for creating hidden or special keys in objects.

You might also like