JavaScript Notes

🔰 Phase 1: JavaScript Fundamentals

Topics:

  • What is JavaScript? How JS runs in browser

  • Variables: letconstvar (and hoisting)

  • Data Types (primitive vs non-primitive)

  • Type Conversion & Coercion

  • Operators: arithmetic, comparison, logical, ternary

  • Conditional statements: ifelseswitch

  • Loops: forwhiledo whilefor...infor...of

  • Functions:

    • Declaration vs Expression

    • Parameters vs Arguments

    • Arrow Functions

    • IIFE (Immediately Invoked Function Expression)

Practice:

  • Create a basic calculator

  • Write functions like factorial, prime check, palindrome, etc.


🔁 Phase 2: Intermediate JavaScript

Topics:

  • Arrays:

    • Methods: pushpopshiftunshiftslicesplice

    • mapfilterreducefindsomeevery

  • Strings:

    • Methods: splitsubstringincludesindexOfreplace

  • Objects:

    • Object creation, thisObject.keys/values/entries

  • Destructuring (arrays, objects)

  • Spread & Rest operators

  • Template Literals

  • ES6+ Features: let/const, arrow functions, default parameters

  • Callback functions

  • Closures and Scope

  • Higher Order Functions

  • DOM Manipulation Basics

    • document.getElementByIdquerySelector, etc.

    • Event Listeners: clickinputkeydown, etc.

  • Browser Events & Forms

Practice:

  • Todo list app

  • JS Clock/Stopwatch

  • Tip calculator


🧠 Phase 3: Advanced JavaScript 

Topics:

  • Execution Context

  • Call Stack

  • Hoisting

  • Scope Chain

  • Closures

  • Debouncing of Function

  • this keyword in depth

  • bindcallapply

  • Promises & Async/Await

  • Event Loop, Microtasks vs Macrotasks

  • setTimeout, setInterval

  • Debounce & Throttle

  • Modules (import/export)

  • Error Handling (try/catch/finally)

  • JSON & Fetch API

Practice:

  • Build a fake API app using fetch()

  • Create a debounce search box

  • Add loading spinners and async loaders


⚙️ Phase 4: OOP + Functional Programming in JS 

Topics:

  • Constructor Functions

  • Prototypes and Prototype Chain

  • ES6 Classes

  • Inheritance in JS

  • Encapsulation, Abstraction

  • Factory Functions vs Constructor

  • Composition over Inheritance

  • Pure Functions, Immutability

  • Currying, Partial Application

Practice:

  • Build a class-based user system

  • Create a prototype-based cart system


🌐 Phase 5: Browser APIs & Environment 

Topics:

  • Local Storage 

  • Session Storage 

  • Cookies

  • Navigator API

  • Geolocation API

  • Clipboard API

  • History API

  • Web Workers

  • Service Workers 





------------------------------------------------------------------

 Phase 1: JavaScript Fundamentals


1. What is JavaScript? How JS runs in browser?
Ans. 
        
JavaScript is a high-level, interpreted, single-threaded, dynamically typed, prototype-based scripting language used to make web pages interactive. It runs in the browser alongside HTML and CSS to create rich, dynamic web applications.

It follows the ECMAScript specification and supports event-driven, functional, and object-oriented programming styles.

Example use-cases:

  • Form validation

  • Dynamic content update (without refreshing page)

  • Animations, popups

  • API calls, data fetch

How JavaScript Runs in the Browser?

When you open a webpage, the browser loads the HTML → then CSS → then JavaScript.
The JavaScript Engine inside the browser (like V8 in Chrome, SpiderMonkey in Firefox) parses and executes the JS code.

The JS code runs in an Execution Context, and the Call Stack, Heap, Event Loop, and Web APIs work together to make it function asynchronously and non-blocking.

🧪 2. Code Example + Explanation
<!DOCTYPE html>
<html>
  <body>
    <h1 id="greeting">Hello</h1>

    <script>
      const name = "Faraz";
      document.getElementById("greeting").innerText = `Hello, ${name}!`;
    </script>
  </body>
</html>

🔍 What’s Happening In Code:

  1. HTML renders <h1>Hello</h1>

  2. JS code runs inside <script>

  3. name is defined as "Faraz"

  4. The browser’s DOM API (document.getElementById) accesses the <h1> element.

  5. JavaScript changes the content dynamically to say: Hello, Faraz!

So the JS engine reads, parses, executes the code, and uses Web APIs (like DOM) to manipulate the page.


Slang / Easy Mode

Alright, think of JavaScript as the brains of a webpage.

  • HTML is the skeleton

  • CSS is the makeup/clothing

  • JavaScript is the muscle and brain — it makes stuff move, react, and change

When you open a webpage:

Browser reads HTML → applies CSS → then reads JS and says, “Yo JS, time to do your thing!”

The JS engine (like V8 in Chrome) is like a superfast brain that reads the code and says:

“Cool, let me change this text, listen for a button click, and maybe talk to the server.”

And boom — your static page becomes alive. That’s what makes JS powerful.




2. Variables: let, const, var( and hoisting )?
Ans. 

    Variables in JS

A variable is a named container that holds a value. JavaScript provides three ways to declare variables:

KeywordScope Reassignment     RedeclarationHoisted
var    Function-scoped        Yes           Yes       Hoisted (with undefined)
let    Block-scoped        Yes           No       Hoisted (but not initialized)
const    Block-scoped        No           No       Hoisted (but not initialized)

Hoisting

Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope during compilation phase.

  • var is hoisted and initialized as undefined

  • let and const are hoisted but not initialized, they stay in Temporal Dead Zone (TDZ) until their declaration line


Code Example + Explanation

console.log(a);   // undefined
// console.log(b); // ReferenceError
// console.log(c); // ReferenceError

var a = 10;
let b = 20;
const c = 30;

What’s Happening In code?

  1. var a is hoisted and initialized as undefined, so console.log(a) doesn’t crash.

  2. let b and const c are hoisted, but not initialized. So trying to access them before their declaration throws a ReferenceError.

  3. After the declaration line, all three hold their expected values.



3. What is ECMA Script?
Ans. 

    ECMAScript (ES) is the standard specification that defines how the JavaScript language should work. It’s created and maintained by ECMA International under the technical committee TC39.

JavaScript is a programming language that implements ECMAScript. Think of ECMAScript as the rulebook, and JavaScript as a language built from that rulebook.

📌 Major ECMAScript Versions:

  • ES5 (2009): Standardized JS for all browsers

  • ES6 (2015): Huge update – let, const, arrow functions, classes, promises, etc.

  • ES7+ (2016–now): Small yearly updates – includes async/await, optional chaining, etc.

Why it matters?

Knowing ECMAScript versions helps you understand which features are supported where, especially if you're working with older browsers or using Babel/Webpack to transpile code.


Code Example + Explanation

🔹 ES5 Style

var name = "Faraz"; function greet() { console.log("Hello " + name); }

🔹 ES6+ Style

const name = "Faraz"; const greet = () => { console.log(`Hello ${name}`); };

🔍 What's New in ES6:

  • const replaces var

  • Arrow function (=>) is shorter and cleaner

  • Template literals using backticks `` and ${} for interpolation

All of this became possible after ES6 (2015) was introduced.

Slang / Easy Mode

Think of ECMAScript like this:

ECMAScript is the rulebook for JavaScript.
JavaScript is the game we all play.

When new versions of ECMAScript drop (like ES6), it’s like DLC updates for JavaScript — new weapons (like arrow functions), new outfits (let, const), and cooler missions (like async/await).

So when you hear:

“This is an ES6 feature”

They’re basically saying:

“Yo, this cool new thing was added in the 2015 update of JavaScript.”




4. What are Data Types in JS?

Ans.

    In JavaScript, data types define the kind of value a variable can hold. JS data types are divided into:

🔹 Primitive Data Types (immutable)

These store single values and are copied by value:

  • String

  • Number

  • Boolean

  • Undefined

  • Null

  • Symbol (ES6)

  • BigInt (ES11)

🔹 Non-Primitive (Reference) Data Types

These store collections of values or more complex data and are copied by reference:

  • Object

  • Array

  • Function

  • Date, RegExp, etc. (they are objects under the hood)

Code Example + Explanation

// Primitive let x = 10; let y = x; y = 20; console.log(x); // 10 console.log(y); // 20 // Non-Primitive let person1 = { name: "Faraz" }; let person2 = person1; person2.name = "Aditya"; console.log(person1.name); // Aditya console.log(person2.name); // Aditya

🔍 Explanation of Code:

  • x and y are primitives – when y = x, it copies the value of x. So changing y doesn’t affect x.

  • person1 and person2 are non-primitives (objects) – assigning person2 = person1 copies the reference, not the actual object. So modifying person2.name also changes person1.name.

Slang / Easy Mode

Imagine values like cars:

  • Primitive values are like normal cars: when you copy one, you get a whole new car. You scratch one, the other stays fine.

  • Non-primitive values are like keys to the same car. If two people share the same key, and one crashes the car, the car’s gone for both. 💥

So:

  • Primitives → copied by value, changes don’t affect original

  • Non-primitives → copied by reference, both point to the same thing




5. Type Conversion and Type Coercion?

Ans. 

✅ Type Conversion

Type conversion (aka type casting) is the process of manually converting a value from one data type to another using JavaScript functions.

Examples:

Number("5") // 5 String(123) // "123" Boolean(0) // false

✅ Type Coercion

Type coercion is the automatic and implicit conversion of values by JavaScript into another type when performing operations.

JS is a loosely typed language, so it tries to "guess" what type you meant.

Examples:

"5" + 2 // "52" (number is coerced into string) "5" - 2 // 3 (string is coerced into number) false + 1 // 1 null + 1 // 1

Code Example + Explanation

// Type Conversion (Manual) let str = "123"; let num = Number(str); // Explicit conversion console.log(num);          // 123 console.log(typeof num); // number // Type Coercion (Automatic) let a = "5" + 1; // String + Number = "51" let b = "5" - 1; // String - Number = 4 let c = true + 1; // true becomes 1 → 1 + 1 = 2 console.log(a); // "51" console.log(b); // 4 console.log(c); // 2

🔍 Explanation of Code:

  • Number(str) is a manual conversion from string to number.

  • In "5" + 1, JS converts 1 to string and concatenates → "51".

  • In "5" - 1, JS converts "5" to number → 4.

  • In true + 1, true becomes 1 → result is 2.

Slang / Easy Mode

Alright, imagine this:

  • Type conversion is like you changing your clothes yourself → you decide to put on a hoodie (you use String(), Number() etc.).

  • Type coercion is when JavaScript dresses you without asking, based on the situation 😆

"5" + 1 → JS says “Oh! You’re dealing with a string? I’ll convert everything to string.”
"5" - 1 → “Hmm... math? Better treat this like numbers.”
true + 1 → “true is like 1, so let’s just add!”

JS tries to be too helpful sometimes... and that’s what coercion is.



6. Operations: arithmetic, comparison, logical, ternary?

Ans.

    Operators in JavaScript

Operators are symbols or keywords that let you perform operations on values or variables.

    Arithmetic Operators

Used for mathematical operations:

OperatorMeaning        Example
+        Addition     a + b
-        Subtraction     a - b
*        Multiplication     a * b
/        Division         a / b
%        Modulus     a % b
**            Exponentiation     a ** b
++        Increment     a++
--        Decrement     a--


    Comparison Operators

Used to compare values (result: true or false):

OperatorMeaningExample
==            Equal (loose)    5 == "5" → true
===            Equal (strict)    5 === "5" → false
!=            Not equal (loose)    5 != "5" → false
!==            Not equal (strict)    5 !== "5" → true
>            Greater than    10 > 5
<            Less than    5 < 10
>=            Greater than or equal    10 >= 10
<=            Less than or equal    9 <= 10

    Logical Operators

Used to combine boolean values:

Operator        Meaning        Example
&&        ANDa && b
`        Backtecks`Faraz`
!        NOT!a


Ternary Operator

A shorthand for if...else

condition ? exprIfTrue : exprIfFalse

Example:

let age = 18; let result = age >= 18 ? "Adult" : "Minor";

Code Example + Explanation

let a = 10, b = 5; // Arithmetic console.log(a + b); // 15 console.log(a % b); // 0 // Comparison console.log(a > b); // true console.log(a === "10"); // false (strict equality) // Logical console.log(a > 5 && b < 10); // true console.log(a > 20 || b < 10); // true console.log(!false); // true // Ternary let msg = (a > b) ? "A is greater" : "B is greater"; console.log(msg); // "A is greater"

🔍 Explanation:

  • a + b adds numbers

  • a % b gives remainder

  • a === "10" is false because types differ

  • && returns true only if both sides are true

  • || returns true if at least one condition is true

  • !false flips to true

  • Ternary quickly evaluates if...else into one line


Slang / Easy Mode

Alright, let’s break this down like a chill convo:

  • Arithmetic is your math gang: add, subtract, mod – basic stuff.

  • Comparison is the truth detector – checks if values are equal, greater, etc.

    • == is chill and lazy (does type coercion).

    • === is strict and serious (type + value must match).

  • Logical is like conditions squad:

    • && is “both must be true

    • || is “at least one should be true

    • ! is “flip the boolean

  • Ternary?
    It’s just JS saying:

    “Let me handle your if...else in a sexy one-liner.”

            hungry ? "Order Pizza" : "Chill";


7. Conditional statements: if, else, switch?

Ans. 

    What are Conditional Statements?

Conditional statements are used to make decisions in JavaScript based on certain conditions. They control the flow of code depending on whether an expression evaluates to true or false.

if Statement

Executes a block of code if a condition is true.

if (condition) { // code runs if true }

if...else Statement

Provides an alternative block if the condition is false.

if (condition) { // runs if true } else { // runs if false }

else if

Checks multiple conditions in sequence.

if (cond1) { // if cond1 is true } else if (cond2) { // if cond2 is true } else { // if none are true }

switch Statement

Best for checking a value against multiple fixed options (cases).

switch(expression) { case value1: // code break; case value2: // code break; default: // default code }

Code Example + Explanation

let score = 85; // if...else if...else if (score >= 90) { console.log("Grade: A"); } else if (score >= 80) { console.log("Grade: B"); } else { console.log("Grade: C or lower"); } // switch let day = "Saturday"; switch (day) { case "Monday": console.log("Work mode"); break; case "Saturday": case "Sunday": console.log("Weekend vibes"); break; default: console.log("Just another day"); }

Explanation Of Code:

  • First block checks score:

    • 85 is not ≥ 90 → skips "A"

    • 85 ≥ 80 → prints "Grade: B"

  • Second block:

    • day is "Saturday", so it matches case "Saturday" and prints "Weekend vibes"

break is used to stop checking further once a match is found in switch.

Slang / Easy Mode

Here’s how to think about it:

  • if is like asking:

    “Yo, is this true? Cool, run it.”

  • else is like:

    “No? Alright, do this instead.”

  • else if is you going:

    “Okay, maybe it’s not A, but is it B? No? C then?”

  • switch is your menu board:

    “You ordered ‘Saturday’? Here’s your Weekend vibes. Next!”

Use switch when you’re checking a single value against multiple specific cases (like menu items or states). 




8. What is a Function?

Ans. 

A function in JavaScript is a reusable block of code designed to perform a specific task. You can call (or invoke) the function whenever you want that task to run.

Functions help:

  • Avoid repeating code

  • Structure logic into modules

  • Accept inputs (parameters) and optionally return outputs

✅ Syntax (Function Declaration)

function functionName(parameters) { // code block return value; }

Code Example + Explanation

// Function declaration function greet(name) { return `Hello, ${name}!`; } // Function call let message = greet("Faraz"); console.log(message); // Hello, Faraz!

Explanation of Code:

  • function greet(name) → declares a function that takes one input called name

  • return → sends back a result (Hello, Faraz!)

  • greet("Faraz") → calls the function and passes in "Faraz" as the argument

  • message stores the returned string and prints it


Other function types:

// Function expression const square = function(num) { return num * num; }; // Arrow function (ES6) const add = (a, b) => a + b;

Slang / Easy Mode

Imagine a function like a vending machine.

  • You put something in (parameters)

  • It does some secret process (code block)

  • And it spits something out (return)

So:

function greet(name) { return "Hello, " + name; }

is like saying:

“Yo JS, here’s a name — wrap it in a greeting and give it back.”

Also:

  • function is the keyword to start the magic

  • You can call the same function again and again, like reusing a shortcut




9. Declaration vs Expression?

Ans. 

✅ Function Declaration

A function declaration defines a named function using the function keyword at the top level. It is hoisted, meaning it can be called before it appears in the code.

✅ Function Expression

A function expression defines a function and assigns it to a variable. It can be named or anonymous, and it is not hoisted—you must define it before using it.

Example (Formal):

// Function Declaration function sayHello() { return "Hello!"; } // Function Expression const sayHi = function() { return "Hi!"; };

Code Example + Explanation

// Function Declaration console.log(greet()); // ✅ Works due to hoisting function greet() { return "Hey there!"; } // Function Expression console.log(speak()); // ❌ Error: Cannot access 'speak' before initialization const speak = function () { return "What's up!"; };

🔍 Explanation:

  • greet() works even before the function is defined because function declarations are hoisted.

  • speak() throws an error because function expressions are not hoisted. The variable speak exists due to const, but it hasn’t been assigned a function yet when it's called.


Slang / Easy Mode

  • Think of a function declaration like writing down a recipe with a title — it’s already known to the kitchen even if it appears later in the book.

  • A function expression is like a secret note with a recipe that you stick into a box (variable). Until you open the box (define the function), you can’t use it.

Quick comparison:

Feature     Declaration        Expression
          Hoisted?      ✅ Yes        ❌ No
         Can be anonymous?      ❌ No        ✅ Yes/No
         Used before defined?      ✅ Yes        ❌ No



10. Parameters vs Arguments?

Ans. 

✅ Parameters

Parameters are placeholders or variable names defined in the function declaration. They act like input variables the function expects to receive when called.

✅ Arguments

Arguments are the actual values you pass into a function when you call it. They fill in for the parameters.


Example (Formal):

function greet(name) { // 'name' is a parameter console.log("Hello, " + name); } greet("Faraz"); // "Faraz" is the argument

Code Example + Explanation

function add(a, b) { return a + b; // 'a' and 'b' are parameters } const result = add(5, 3); // 5 and 3 are arguments console.log(result); // Output: 8

🔍 Explanation:

  • a and b are the parameters defined in the function header.

  • 5 and 3 are the arguments passed into the function call.

  • The function takes the arguments and assigns them to the parameters internally.

Slang / Easy Mode

  • Parameters = Empty boxes in the function.

  • Arguments = Stuff you put inside those boxes when calling the function.

Think of it like ordering food:

function orderFood(food, drink) { // parameters console.log(`You ordered ${food} and ${drink}`); } orderFood("Pizza", "Cola"); // arguments

Here, the chef (function) doesn't know what to cook until you tell him (pass arguments). The placeholders (food, drink) are like blanks to fill.




11. Arrow Functions?

Ans. 


Arrow functions, introduced in ES6 (ECMAScript 2015), are a shorter syntax for writing function expressions in JavaScript.
They do not have their own this, arguments, super, or new.target, which makes them behave differently than regular functions in certain contexts (especially in OOP or when using this inside functions).

Example (Formal):
// Traditional function expression
const add = function(a, b) {
  return a + b;
};

// Arrow function
const addArrow = (a, b) => a + b;


Code Example + Explanation

// Arrow Function Example const greet = (name) => { return `Hello, ${name}!`; }; console.log(greet("Faraz")); // Output: Hello, Faraz!

Explanation:

  • const greet = — We’re storing the function in a constant.

  • (name) — This is the parameter.

  • => — This is the arrow, representing the function body.

  • { return ... } — You return a value just like regular functions.


You can shorten arrow functions further if there’s only one expression:

const greet = name => `Hello, ${name}!`;
  • No return or {} needed for single-line expressions.

  • Also, you can skip parentheses if there's only one parameter.


Special Note:

Arrow functions do not bind this like regular functions. This is useful in callbacks.

const obj = { name: "Faraz", greet: function () { setTimeout(() => { console.log(`Hi, I am ${this.name}`); }, 1000); } }; obj.greet(); // ✅ Works because arrow function uses outer `this`

Slang / Easy Mode

Arrow functions are like the lazy guy’s way of writing functions.

Instead of:

function doSomething(x) { return x * 2; }

You just go:

const doSomething = (x) => x * 2;
  • They’re short.

  • They look clean.

  • But be careful — they don't have their own this, so don’t use them when you need this (like in class methods or certain object contexts).



12. IIFE (Immediately Invoked Function Expression)?

Ans. 

    An IIFE (Immediately Invoked Function Expression) is a function in JavaScript that is defined and executed immediately after it's created. It helps to create a private scope and is often used to avoid polluting the global namespace.


Formal Example:

(function () { console.log("IIFE ran!"); })();

It's wrapped in parentheses to turn it into an expression.
It’s immediately called with () at the end.


Code Example + Explanation

// IIFE to create a private variable (function () { const secret = "Top secret code"; console.log(secret); // Output: Top secret code })(); console.log(secret); // ❌ ReferenceError: secret is not defined

Explanation:

  • We define the function (function () { ... })

  • And call it immediately with ()

  • The variable secret is scoped inside the IIFE, so it doesn't leak outside.

  • This is a classic pattern to avoid polluting global scope.



You can also write IIFE with arrow functions:

(() => { console.log("Arrow IIFE runs too!"); })();

Slang / Easy Explanation

Think of IIFE as a function that says:

“Bro, I don't wanna be reused. Just run me right now and leave.”

🔒 It’s like a one-time self-destructing function that runs instantly and doesn’t mess up your global code.

You wrap it in () so JS knows it’s a function expression, and then slap () again to execute it.


🔧 Use Cases:

  • To encapsulate variables without leaving trash in global scope.

  • In modules or polyfills.

  • For init code that only needs to run once.















----------------------------------------------------------------------------------------------------------

Phase 2: Intermediate JavaScript

1. Array?

Ans. 

    An Array in JavaScript is an ordered collection of elements (values), where each value is stored at a numeric index, starting from 0.
Arrays can hold multiple data types, including strings, numbers, objects, or even other arrays.

Arrays are non-primitive data types and are mutable.

✅ Example:

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

Here:

  • "apple" is at index 0

  • "banana" is at index 1

  • "cherry" is at index 2

 Code Example + Explanation:

const numbers = [10, 20, 30, 40]; // Accessing elements console.log(numbers[0]); // 10 // Updating a value numbers[2] = 35; console.log(numbers); // [10, 20, 35, 40] // Adding a value numbers.push(50); // Adds at the end console.log(numbers); // [10, 20, 35, 40, 50] // Removing the last element numbers.pop(); // Removes 50 console.log(numbers); // [10, 20, 35, 40] // Getting the length console.log(numbers.length); // 4

🔍 Explanation Of Code:

  • numbers[0] → accesses the first element

  • numbers[2] = 35 → updates the third element

  • .push() → adds to the end

  • .pop() → removes from the end

  • .length → tells total number of elements

Other useful methods:

  • .shift() → removes first element

  • .unshift(val) → adds at the beginning

  • .splice() → adds/removes anywhere

  • .slice() → creates a shallow copy

  • .includes() → checks if value exists

 Slang / Easy Explanation:

Think of an array like a row of boxes 🧰, each with a number on it (the index), and each box can hold anything—fruits, numbers, objects, you name it.

You can:

  • Open a box (array[index])

  • Change what’s inside (array[index] = newVal)

  • Add a new box at the end (push)

  • Remove the last box (pop)

  • Check how many boxes (length)

It’s your own mini storage unit for data—throw stuff in, grab it later, shuffle things around.


2. Methods on Arrays: push, pop, shift, unshift, slice, splice?

Ans. 

Formal Definitions with Examples

MethodDefinition
push()                Adds element(s) to the end of an array.
pop()                Removes the last element from an array.
shift()                Removes the first element from an array.
unshift()                Adds element(s) to the beginning of an array.
slice()                Returns a shallow copy of a portion of the array (doesn’t modify it).
splice()                Adds/removes elements from a given position in the array (modifies it).

🧪 2. Code Examples + Explanation

let arr = [1, 2, 3, 4, 5]; // push arr.push(6); // [1, 2, 3, 4, 5, 6] // pop arr.pop(); // [1, 2, 3, 4, 5] // unshift arr.unshift(0); // [0, 1, 2, 3, 4, 5] // shift arr.shift(); // [1, 2, 3, 4, 5] // slice (non-destructive) let sliced = arr.slice(1, 4); // [2, 3, 4] console.log(arr); // original array stays: [1, 2, 3, 4, 5] // splice (destructive) arr.splice(2, 1); // removes 1 element at index 2 => [1, 2, 4, 5] arr.splice(1, 0, 9, 8); // inserts 9 and 8 at index 1 => [1, 9, 8, 2, 4, 5]

3. Slang / Easy Mode:

  • 🧃 push() = slap stuff at the end

  • 🪓 pop() = chop off the last item

  • 🚪 shift() = kick out the first guy

  • 🚶 unshift() = bring in new guys at the front

  • ✂️ slice() = take a clean copy of a part (doesn’t mess with original)

  • 🛠️ splice() = surgery: cut, insert, remove anything from anywhere




3. Advance Methods on Arrays: map, filter, reduce, find, some, every?

Ans. 

Formal Definitions with Examples

MethodPurpose
map()        Transforms each element and returns a new array
filter()        Returns a new array with elements that pass a test
reduce()        Reduces array to a single value using a callback
find()        Returns the first element that matches a condition
some()        Returns true if any element passes a condition
every()        Returns true if all elements pass a condition

🧪 2. Code Examples + Explanation

const nums = [1, 2, 3, 4, 5]; // map: multiply each by 2 const doubled = nums.map(n => n * 2); // [2, 4, 6, 8, 10] // filter: keep even numbers const evens = nums.filter(n => n % 2 === 0); // [2, 4] // reduce: sum all numbers const total = nums.reduce((acc, curr) => acc + curr, 0); // 15 // find: find first number > 3 const found = nums.find(n => n > 3); // 4 // some: is there any number > 4? const anyAbove4 = nums.some(n => n > 4); // true // every: are all numbers < 10? const allBelow10 = nums.every(n => n < 10); // true

3. Slang / Easy Mode:

  • 🔁 map() = “change every item and give me the new list”

  • 🔍 filter() = “keep only the stuff that passes the test”

  • 🧮 reduce() = “boil it all down to one value”

  • 🎯 find() = “give me the first match”

  • some() = “anyone pass?”

  • every() = “everyone pass?”




4. Strings?

Ans. 

Formal Definition with Example

A string in JavaScript is a sequence of characters enclosed in single ('), double ("), or backticks (`). Strings are immutable—once created, they cannot be changed.

Example:

let str1 = 'Hello'; let str2 = "World"; let str3 = `Hello, ${str2}`; // Template literal

🧪 2. Code Example with Explanation

let name = "Faraz"; let greeting = "Hello " + name; // Concatenation let length = name.length; // 5 let upper = name.toUpperCase(); // "FARAZ" let lower = name.toLowerCase(); // "faraz" let firstChar = name.charAt(0); // "F" let includesZ = name.includes("z"); // true let sliced = name.slice(1, 4); // "ara" let replaced = name.replace("a", "o"); // "Foraz" let temp = `Hi ${name}, welcome!`; // Template string

Explanation:

  • .length: total characters

  • .toUpperCase(), .toLowerCase(): casing

  • .charAt(n): character at index

  • .includes(): check substring

  • .slice(start, end): extract part

  • .replace(old, new): replace first match

  • Template literal: embed variables easily


 3. Easy / Slang Explanation

  • A string is just text like "Yo!" or 'Bro'

  • You can mix it, slice it, check it, replace it, or shout it (uppercase)

  • Backticks (`) let you plug in variables like:
    `Hello ${name}` = "Hello Faraz"

✅ Think of strings as quotes wrapped around letters, and JS gives you tools to mess with them.





5. Methods on Strings: split, substring, includes, indexOf, replace?

Ans. 

Formal Definition with Example

JavaScript provides built-in string methods that help manipulate or retrieve parts of a string:

MethodDescription
split()        Splits a string into an array using a separator
substring()        Returns part of the string between two indexes
includes()        Checks if a string contains a substring
indexOf()        Returns the first index of a substring, or -1 if not found
replace()        Replaces the first match of a substring with a new value

Example:
let str = "JavaScript is awesome!";

🧪 2. Code Example with Explanation

let text = "Hello, Faraz Mohammad"; // 1. split let words = text.split(" "); console.log(words); // ['Hello,', 'Faraz', 'Mohammad'] // 2. substring let part = text.substring(7, 12); console.log(part); // 'Faraz' // 3. includes let hasMohammad = text.includes("Mohammad"); console.log(hasMohammad); // true // 4. indexOf let index = text.indexOf("Faraz"); console.log(index); // 7 // 5. replace let newText = text.replace("Faraz", "Ethesham"); console.log(newText); // Hello, Ethesham Mohammad

Explanation:

  • split(" ") → breaks string into array using spaces.

  • substring(7, 12) → extracts characters from index 7 to 11.

  • includes("Mohammad") → returns true if that word exists.

  • indexOf("Faraz") → returns 7, the start index of the word.

  • replace("Faraz", "Ethesham") → swaps only the first match.


😎 3. Easy / Slang Explanation

  • split() → “Bro, cut my string into pieces” (usually by spaces or commas)

  • substring() → “Gimme just this slice of it”

  • includes() → “Does this text have this word in it?”

  • indexOf() → “Where does this word start?”

  • replace() → “Swap this word with something cooler”

🧠 Example:

"JS is 💥".includes("💥") // true



6. Objects?

Ans. 

Formal Definition with Example

➤ What is an Object in JavaScript?

An object is a non-primitive data type that allows you to store key-value pairs. It’s used to represent real-world entities like users, cars, or settings.

📦 Example:

const user = { name: "Faraz", age: 22, isStudent: true };

Here:

  • "name", "age", "isStudent" are keys (also called properties)

  • "Faraz", 22, true are their corresponding values


🧪 2. Code Example with Explanation

const car = { brand: "Tesla", model: "Model 3", year: 2022, start: function() { return "Car started"; } }; // Access values console.log(car.brand); // Tesla console.log(car["model"]); // Model 3 // Modify property car.year = 2023; // Add new property car.color = "Red"; // Delete property delete car.model; // Call method console.log(car.start()); // Car started

💡 Key Concepts:

  • Dot notation: car.brand

  • Bracket notation: car["model"]

  • Methods: Functions inside objects

  • Dynamic changes: You can add/delete keys any time


😎 3. Easy / Slang Explanation

Think of objects like folders 🔐 with labeled sections:

const myLife = { mood: "coding", time: "night", snack: "coffee" };
  • You can peek inside (myLife.mood)

  • You can add new things (myLife.hobby = "hacking")

  • You can change stuff (myLife.snack = "green tea")

  • You can delete junk (delete myLife.time)



7. Object creation, this, Object.keys/values/entries ?

Ans. 

🔧 1. Object Creation

🧠 Formal Definition:

There are multiple ways to create objects in JavaScript:

  1. Object literals

  2. new Object() constructor

  3. Object.create()

📦 Example:

// Literal const user1 = { name: "Faraz", age: 22 }; // Constructor const user2 = new Object(); user2.name = "Faraz"; // Object.create() const proto = { greet: () => "Hi!" }; const user3 = Object.create(proto); user3.name = "Faraz";

🧪 Code + Explanation:

const user = { name: "Faraz", age: 22 }; const user2 = new Object(); user2.name = "Faraz"; const prototypeUser = { intro: function() { return "Hello"; } }; const user3 = Object.create(prototypeUser); user3.name = "Faraz"; console.log(user3.intro()); // Hello
  • Object literal is the most common

  • Object.create() allows prototype-based inheritance


😎 Slang Explain:

Making objects is like building your own mini JSON gang 👊

  • const obj = {} → Fast & easy (like frying Maggi 🍜)

  • new Object() → Classic old-school but kinda boring 📦

  • Object.create() → You copy from someone else's blueprint (like borrowing a classmate’s notes 😅)


👤 2. this Keyword

🧠 Formal Definition:

In JavaScript, this refers to the context in which a function is executed. In objects, it usually refers to the object itself.

📦 Example:

const person = { name: "Faraz", greet: function () { return "Hi, " + this.name; } };

🧪 Code + Explanation:

const user = { name: "Faraz", age: 22, sayHi() { console.log("Hi " + this.name); } }; user.sayHi(); // Hi Faraz const greet = user.sayHi; greet(); // Hi undefined (in strict mode, or global object in loose mode)
  • Inside sayHi(), this refers to user

  • Outside an object, this might point to window (in browsers)


😎 Slang Explain:

this is like that one friend who acts differently depending on where they are 🤪

  • Inside an object → this is that object

  • Inside a normal function → it might be undefined or the global scope

  • Inside arrow function → it doesn’t have its own this, it borrows from above


🗝️ 3. Object.keys / values / entries

🧠 Formal Definition:

These are built-in JS methods to extract info from objects:

  • Object.keys(obj) → returns array of keys

  • Object.values(obj) → returns array of values

  • Object.entries(obj) → returns array of [key, value] pairs

📦 Example:

const user = { name: "Faraz", age: 22, isDev: true }; console.log(Object.keys(user)); // ["name", "age", "isDev"] console.log(Object.values(user)); // ["Faraz", 22, true] console.log(Object.entries(user)); // [["name", "Faraz"], ["age", 22], ["isDev", true]]

🧪 Code + Explanation:

const car = { brand: "Tesla", year: 2023, color: "Black" }; console.log(Object.keys(car)); // ["brand", "year", "color"] console.log(Object.values(car)); // ["Tesla", 2023, "Black"] Object.entries(car).forEach(([key, value]) => { console.log(`${key} => ${value}`); });
  • Useful for loops, transformations, logging

  • Object.entries() is best when you need both key and value


😎 Slang Explain:

These are like your object’s cheat codes 🎮

  • keys() → show me what drawers you got 🗂️

  • values() → gimme what’s inside them

  • entries() → full list of drawer name + stuff inside




8. Destructuring, Spread, Rest, or Optional chaining?

Ans. 

 1. Destructuring

🔹Formal Definition:

Destructuring is a JavaScript expression that allows unpacking values from arrays or properties from objects into distinct variables.

Example:

const person = { name: "Faraz", age: 21 }; const { name, age } = person;

or

const arr = [1, 2, 3]; const [a, b, c] = arr;

Code Example:

const arr = [1, 2, 3]; const [a, b, c] = arr; const user = { username: "faraz", email: "faraz@example.com" }; const { username, email } = user;

Explanation:

  • [a, b, c] = arr: takes values from the array arr and assigns them to variables a, b, c.

  • { username, email } = user: pulls out username and email from the user object directly.

Easy/Slang:

Destructuring is like unpacking your backpack into labeled shelves. Instead of saying backpack.bottle, you just say bottle because you already pulled it out.


🔹 2. Spread Operator ...

Formal Definition:

The spread operator (...) allows an iterable (like an array or object) to be expanded in places where multiple elements/arguments are expected.

Example:

const arr1 = [1, 2]; const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]

Code Example:

const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; const nums = [5, 6, 7]; const copy = [...nums];

Explanation:

  • ...obj1 spreads the properties of obj1 into obj2.

  • ...nums copies all elements of nums into copy.

Easy/Slang:

Spread is like spilling out the contents of a box into another box. Whatever is inside just gets thrown in automatically.


🔹 3. Rest Operator ...

Formal Definition:

The rest operator (...) collects all remaining elements into a single array or object. It's the opposite of spread.

Example:

function sum(...numbers) { return numbers.reduce((a, b) => a + b); }

Code Example:

const [first, ...rest] = [1, 2, 3, 4]; // first = 1, rest = [2, 3, 4] const { a, ...others } = { a: 1, b: 2, c: 3 }; // a = 1, others = { b: 2, c: 3 }

Explanation:

  • In array destructuring: grabs first, then dumps the rest in rest.

  • In object destructuring: pulls out a, and collects remaining keys in others.

Easy/Slang:

Rest is like saying “put everything else in this bag.” You pick a few things, and the rest go in one bucket.


🔹 4. Optional Chaining ?.

Formal Definition:

Optional chaining (?.) allows accessing deeply nested properties without explicitly checking for the existence of each level.

Example:

const user = {}; console.log(user?.profile?.email); // undefined (no error)

Code Example:

const user = { profile: { name: "Faraz", contact: { email: "faraz@example.com" } } }; console.log(user?.profile?.contact?.email); // "faraz@example.com" console.log(user?.profile?.social?.twitter); // undefined, doesn't throw error

Explanation:

  • If any part before ?. is null/undefined, it short-circuits and returns undefined instead of throwing an error.

Easy/Slang:

Optional chaining is like tiptoeing into a house—if the door’s locked (i.e. undefined), you just walk away instead of crashing in and dying with an error.



9. Template Literals?

Ans. 

1. Formal Definition with Example

Template literals (also called template strings) are string literals that allow embedded expressions. They are enclosed by backticks (`) instead of single (') or double (") quotes. You can use ${expression} syntax inside them to embed variables or any JS expression directly into the string.

Example:

let name = "Faraz"; let msg = `Hello, ${name}! Welcome back.`;

2. Code Example with Explanation

let user = "Faraz"; let age = 22; // Using template literals let intro = `My name is ${user} and I am ${age} years old.`; console.log(intro);

Explanation:

  • We're using backticks (`) to define a template literal.

  • Inside the string, ${user} and ${age} are placeholders.

  • JavaScript evaluates those expressions and injects their values into the final string.

  • Output: "My name is Faraz and I am 22 years old."

You can also use expressions:

let a = 5, b = 3; console.log(`The sum is ${a + b}`); // "The sum is 8"

3. Slang / Easy Explanation

Think of template literals like smart strings. Instead of breaking the string or adding + to join stuff, you just wrap everything in backticks ` and throw your variables inside ${} — it’s clean, readable, and powerful.

Instead of:

"Hello " + name + ", how are you?"

You can do:

`Hello ${name}, how are you?`

Much cleaner. It’s like string building on steroids.



10. ES6+ Features: let/const, arrow functions, default parameters?

Ans. 

✅ 1. Formal Definitions with Examples

a. let and const

  • let: Declares a block-scoped variable, can be reassigned.

  • const: Declares a block-scoped constant, cannot be reassigned.

Example:

let count = 5; count = 10; // ✅ allowed const PI = 3.14; PI = 3.15; // ❌ Error: Assignment to constant variable

b. Arrow Functions

Arrow functions are a shorter way to write functions using =>. They do not bind their own this (lexical this).

Example:

const greet = (name) => `Hello, ${name}`;

c. Default Parameters

Allows setting default values for function parameters if no value (or undefined) is passed.

Example:

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

✅ 2. Code Examples with Explanation

// let and const let score = 50; score += 10; const maxScore = 100; // maxScore = 110; // ❌ This will throw an error // Arrow Function const add = (a, b) => a + b; // Default parameter const welcome = (user = "Anonymous") => `Welcome, ${user}`; console.log(add(5, 10)); // 15 console.log(welcome("Faraz")); // "Welcome, Faraz" console.log(welcome()); // "Welcome, Anonymous"

Explanation:

  • let is used when the value may change.

  • const is for fixed values.

  • Arrow functions make function syntax shorter and don't create their own this.

  • Default parameters help avoid undefined when arguments are missing.


✅ 3. Slang / Easy Explanation

  • let is like a flexible variable. You can change it later.

  • const is like “locked”. Once you assign it, you can’t change it.

  • Arrow functions = chill, short, modern way to write functions.

  • Default parameters = backup values. If you don’t pass something, JS uses the default.




11. Callback functions?

Ans. 

✅ 1. Formal Definition with Example

A callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete some action.

Example:

function greet(name, callback) { console.log("Hi " + name); callback(); // invoke the callback } function sayBye() { console.log("Bye!"); } greet("Faraz", sayBye);

✅ 2. Code Example with Explanation

function fetchData(callback) { setTimeout(() => { console.log("Data fetched!"); callback(); // call after task is done }, 1000); } function processData() { console.log("Processing data..."); } fetchData(processData);

Explanation:

  • fetchData simulates an async task.

  • Once it's done, it calls processData.

  • processData is the callback function, used here to run after fetching data.


✅ 3. Easy/Slang Explanation

  • A callback is just a function you give to another function, saying:

    "Hey, when you're done, call me back."

  • It’s like:

    “Mom, I’m going to the store. Call me when dinner’s ready.”




12. Closures and Scope?

Ans. 

✅ 1. Formal Definition with Example

Scope

Scope defines where variables and functions are accessible in your code.

  • Global scope – accessible anywhere.

  • Function/local scope – accessible only inside the function.

  • Block scope – accessible only inside {} (like in if, for, etc.) with let and const.

Closure

A closure is a function that remembers the variables from its outer scope, even after the outer function has finished executing.

Example:

function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2

✅ 2. Code Example with Explanation

function createCounter() { let num = 0; // this is in outer scope return function () { num += 1; // inner function uses outer variable return num; }; } const counter1 = createCounter(); console.log(counter1()); // 1 console.log(counter1()); // 2 const counter2 = createCounter(); console.log(counter2()); // 1

Explanation:

  • createCounter creates a private num.

  • The returned function “remembers” num even after createCounter is done → that’s a closure.

  • Each call to createCounter gives a new private scope.


✅ 3. Easy/Slang Explanation

  • Scope is just “where your variables live”.

  • Closure is like:

    “Even after the house party is over (outer function), your best friend (inner function) still remembers the snacks (variables).”

  • It’s like giving someone a backpack (closure) filled with stuff from the outer function, and they carry it wherever they go.



13. Higher Order Functions?

Ans. 

✅ 1. Formal Definition with Example

A Higher-Order Function (HOF) is a function that either:

  • Takes another function as an argument, or

  • Returns another function.

They treat functions as "first-class citizens".

Example:

function greetUser(name) { return `Hello, ${name}!`; } function processUser(name, callback) { return callback(name); } console.log(processUser("Faraz", greetUser)); // Hello, Faraz!

✅ 2. Code Example with Explanation

// HOF that takes a function function calculate(a, b, operation) { return operation(a, b); } // Passing functions as arguments function add(x, y) { return x + y; } function multiply(x, y) { return x * y; } console.log(calculate(5, 3, add)); // 8 console.log(calculate(5, 3, multiply)); // 15

Explanation:

  • calculate is the higher-order function.

  • It accepts a function (operation) as an argument and invokes it.

  • add and multiply are passed dynamically.


✅ 3. Easy/Slang Explanation

Think of Higher-Order Functions like a customizable machine — you plug in a different tool (function) and it does the job differently.

You can tell a HOF:

“Hey, do something with this input... and btw, here’s how I want it done (a function).”

Example in real life:

  • You give a chef (HOF) a potato (data) and a recipe (callback function).

  • Depending on the recipe, the chef makes fries or mashed potatoes.



14. DOM Manipulation Basics?

Ans. 

✅ 1. Formal Definition with Example

The DOM (Document Object Model) is a tree-like structure representing your HTML in the browser. DOM manipulation is the process of using JavaScript to interact with, change, or create HTML elements dynamically.

Example:

<p id="text">Hello</p> <script> const para = document.getElementById("text"); para.textContent = "Hi there!"; </script>

✅ 2. Code Example with Explanation

<button id="btn">Click Me</button> <p id="output"></p> <script> const btn = document.getElementById("btn"); const output = document.getElementById("output"); btn.addEventListener("click", () => { output.textContent = "Button clicked!"; output.style.color = "green"; }); </script>

What’s happening:

  • getElementById() grabs elements by ID.

  • addEventListener() listens for events (like click).

  • .textContent updates the text inside the element.

  • .style modifies CSS directly via JS.


✅ 3. Easy/Slang Explanation

DOM is like the blueprint of your webpage. JS is the mechanic that tweaks stuff on the fly.

You can use JavaScript to:

  • Grab elements

  • Change their content

  • Change their styles

  • Add/remove elements

  • Listen to clicks, hovers, typing, etc.


✅ Common DOM methods to know:

TaskMethod
Get by ID    getElementById()
Get by class    getElementsByClassName()
Get by tag    getElementsByTagName()
Modern query    querySelector() / querySelectorAll()
Change text    .textContent, .innerText, .innerHTML
Change styles    element.style.property = value
Event handling    addEventListener()



15. document.getElementById, querySelector, etc.?

Ans. 

✅ 1. Formal Definition with Example

These are DOM selection methods used to fetch HTML elements from the document for manipulation.

MethodDescriptionReturns
getElementById(id)Selects an element by IDSingle Element
getElementsByClassName(class)Selects all elements with that classHTMLCollection (live)
getElementsByTagName(tag)Selects all elements with that tagHTMLCollection (live)
querySelector(selector)Returns first element matching any valid CSS selectorSingle Element
querySelectorAll(selector)Returns all elements matching a CSS selectorStatic NodeList

Example:
<div id="main" class="box">Hello</div>

const byId = document.getElementById("main"); const byClass = document.getElementsByClassName("box"); const byTag = document.getElementsByTagName("div"); const qs = document.querySelector(".box"); const qsa = document.querySelectorAll("div.box");

✅ 2. Code Example with Explanation

<ul> <li class="item">Item 1</li> <li class="item">Item 2</li> </ul> <script> const firstItem = document.querySelector(".item"); // First <li> const allItems = document.querySelectorAll(".item"); // NodeList of both <li> const ulTag = document.getElementsByTagName("ul")[0]; // First <ul> const byClass = document.getElementsByClassName("item"); // HTMLCollection firstItem.style.color = "red"; allItems.forEach(item => item.style.fontWeight = "bold"); </script>
  • querySelectorAll returns a static list → supports forEach

  • getElementsByClassName returns a live collection → needs Array.from() to use array methods


✅ 3. Easy/Slang Explanation

Think of getElementById() as “Yo, gimme that one guy with this ID.”
querySelector() is more like “Find me the first match that looks like this CSS pattern.”
querySelectorAll() says “Get all the things that match this pattern.”


✅ Summary Cheat:

SelectorUse CaseReturns
getElementById("id")Fastest for unique IDsElement
getElementsByClassName("class")Multiple elementsLive HTMLCollection
getElementsByTagName("tag")All matching tagsLive HTMLCollection
querySelector("css")First match via CSSElement
querySelectorAll("css")All matches via CSSStatic NodeList



16. Event Listeners: click, input, keydown, etc.?

Ans. 

✅ 1. Formal Definition with Example

Event Listeners in JavaScript let you respond to user interactions (clicks, typing, hovering, etc.).

They are added using:

element.addEventListener("event", callback)

Common Event Types:

EventTriggered When...
clickUser clicks an element
inputUser types or modifies input
keydownAny key is pressed down
keyupKey is released
mouseoverMouse hovers over element
submitA form is submitted


✅ 2. Code Example with Explanation
<input id="nameInput" placeholder="Type something" /> <button id="myBtn">Click Me</button> <script> const input = document.getElementById("nameInput"); const button = document.getElementById("myBtn"); // Click Event button.addEventListener("click", () => { alert("Button was clicked!"); }); // Input Event input.addEventListener("input", (e) => { console.log("Typed:", e.target.value); }); // Keydown Event input.addEventListener("keydown", (e) => { console.log("Key pressed:", e.key); }); </script>

✅ 3. Easy/Slang Explanation

Think of addEventListener like telling your HTML element:

“Hey bro, when this thing gets clicked / typed into / pressed, let me know, I’ll handle it!”

You’re literally adding a listener to the DOM element, waiting for the user to do something.


✅ Bonus: Removing Event Listeners

function logInput(e) { console.log(e.target.value); } input.addEventListener("input", logInput); // Later, remove it input.removeEventListener("input", logInput);

You must use the same function reference to remove it.





17. Browser Events & Forms?

Ans. 

✅ 1. Formal Definition with Example

Browser Events are interactions the browser detects — like clicks, form submits, loading a page, resizing, etc.

Forms in HTML (<form>) trigger special events like submit, change, and input that let you handle user data.


📌 Common Browser + Form Events:

EventWhat it does
loadFires when page fully loads
DOMContentLoadedFires when DOM is ready (before images/CSS)
resizeWindow size changes
submitA form is submitted
changeInput value changes (on blur)
inputRuns as user types (real-time input)


✅ 2. Code Example with Explanation
<form id="myForm"> <input name="username" type="text" /> <button type="submit">Submit</button> </form> <script> // Wait for DOM document.addEventListener("DOMContentLoaded", () => { console.log("DOM fully loaded"); }); // Form handling const form = document.getElementById("myForm"); form.addEventListener("submit", (e) => { e.preventDefault(); // Prevents page reload const data = new FormData(form); const username = data.get("username"); console.log("Submitted username:", username); }); </script>

🧠 FormData is used to extract key/value pairs from the form easily.


✅ 3. Easy/Slang Explanation

Browser events = browser saying “yo something happened!”

Forms = places where users type stuff. You can hijack the submit button and say:

“Hold up, don’t reload — lemme check the data first.”

You can listen to form events, prevent reload, and do things like validate, save to DB, or show messages.


⚡ Bonus: Auto Detecting Input Changes


const input = document.querySelector("input"); input.addEventListener("input", (e) => { console.log("Typing:", e.target.value); }); input.addEventListener("change", (e) => { console.log("Changed after blur:", e.target.value); });










--------------------------------------------------------------------------

🧠 Phase 3: Advanced JavaScript 

1. Execution Context?

Ans. 

1. Formal Definition + Example:

Execution Context in JavaScript is an abstract concept that defines the environment in which code is evaluated and executed. It contains information such as:

  • Variable Object (VO) – stores function arguments, variable and function declarations.

  • Scope Chain – defines the accessibility of variables.

  • this Binding – refers to the object to which the function belongs.

There are 3 main types of execution contexts:

  • Global Execution Context (GEC) – created by default in the browser or Node.js.

  • Functional Execution Context (FEC) – created whenever a function is invoked.

  • Eval Execution Context – created when code is run inside eval() (rarely used).

Example:

var name = "Faraz"; function greet() { var message = "Hello " + name; console.log(message); } greet();
  • First, the Global Execution Context is created.

  • When greet() is called, a Function Execution Context is created for it.


2. Code Example + Explanation:

var x = 10; function foo() { var y = 20; console.log(x + y); } foo(); // Outputs: 30

Execution Flow:

  • JavaScript engine first creates the Global Execution Context.

    • x is allocated memory and set to 10.

    • foo function is also stored in memory.

  • When foo() is called:

    • A new Function Execution Context is pushed onto the Execution Stack.

    • y is declared inside foo's local context.

    • The function has access to both x (from global scope) and y (local).


3. Easy/Slang Explanation:

Think of Execution Context like a "room" where your code runs:

  • The global room is the main area where the party starts.

  • Every time you run a function, JavaScript creates a new room (function context) just for that function to do its thing.

  • Inside each room, JS keeps track of:

    • Stuff declared in that room (variables).

    • What the word this means in that room.

    • What other rooms (scopes) this room can peek into.

Once a function finishes, its room is cleaned up and thrown away.



2. Call Stack?

Ans. 

1. Formal Definition + Example:

The Call Stack is a stack data structure used by the JavaScript engine to keep track of function calls (execution contexts). It follows LIFO (Last-In, First-Out) – the last function pushed in is the first to be popped out.

Whenever a function is called:

  • A new execution context is created and pushed onto the call stack.

  • When the function finishes executing, its context is popped off.

Example:
function greet() { console.log("Hello"); } function welcome() { greet(); console.log("Welcome!"); } welcome();

Call Stack Flow:

  1. Global() pushed

  2. welcome() pushed

  3. greet() pushed

  4. greet() popped

  5. welcome() popped

  6. Global() popped


2. Code Example + Explanation:

function a() { console.log("Inside A"); b(); } function b() { console.log("Inside B"); c(); } function c() { console.log("Inside C"); } a();

Call Stack Execution:

  1. Global Execution Context → pushed

  2. a() called → a Execution Context → pushed

  3. b() called → b Execution Context → pushed

  4. c() called → c Execution Context → pushed

  5. c() finishes → popped

  6. b() finishes → popped

  7. a() finishes → popped

  8. Program ends → global context popped


3. Easy/Slang Explanation:

Imagine a stack of plates. Each time you call a function, a new plate goes on top. When the function finishes, that plate gets taken off. That’s the Call Stack.

You can't take a plate from the middle or bottom – only the top one. That’s why last called = first done.

If you keep stacking plates without removing them, it overflows – that’s a stack overflow error.

Example:

function repeat() { repeat(); // infinite recursion } repeat(); // StackOverflowError 💥



3. Stack Overflow?

Ans. 

1. Formal Definition + Example:

A Stack Overflow occurs when the Call Stack exceeds its maximum size, typically due to infinite recursion or deeply nested function calls that never terminate.

Each function call adds a frame (execution context) to the stack. If too many frames are added without being removed, the memory limit is reached, and the JavaScript engine throws a "RangeError: Maximum call stack size exceeded".

Example:
function recurse() { recurse(); // calls itself endlessly } recurse(); // ❌ Stack overflow

2. Code Example + Explanation:

function countDown(n) { console.log(n); countDown(n - 1); } countDown(100000); // Stack overflow after too many recursive calls

Explanation:

  • countDown calls itself with n - 1 forever.

  • The call stack keeps adding a new frame for each call.

  • After ~10,000–20,000 calls (depends on engine/browser), memory limit hits → 💥 Stack Overflow.


3. Easy/Slang Explanation:

Imagine you're stacking books one by one on a table (each book = a function call). If you never stop stacking, eventually the pile gets too high and collapses — that’s stack overflow.

In JS:

  • It happens when a function keeps calling itself (like an idiot stuck in a loop) and never ends.

  • Browser says: “Yo, I’m out of memory. Shut it down!” 💀


Fix Example:

function countDown(n) { if (n <= 0) return; // ✅ Base condition to stop recursion console.log(n); countDown(n - 1); }

Always have a base case in recursion or rewrite with loops if stack usage is too high.



4. Tail Call Optimization (TCO)?

Ans. 

1. Formal Definition + Example:

Tail Call Optimization is a feature where the JavaScript engine reuses the current function’s stack frame for a function call if the call is the last operation in the function (i.e., in the tail position), thus preventing stack overflow.

It's only supported in strict mode and only in some JS engines (e.g., Safari – but not Chrome/V8 or Node.js yet).

Example (TCO-compatible style):
"use strict"; function factorial(n, acc = 1) { if (n <= 1) return acc; return factorial(n - 1, acc * n); // Tail call } factorial(100000); // ✅ Won’t overflow if TCO is supported

2. Code Example + Explanation:

Without TCO:

function sum(n) { if (n === 0) return 0; return n + sum(n - 1); // Not a tail call because there's still work (n + ...) }

Each call needs to remember n to do the addition after recursion returns → stack builds up → 💥 stack overflow.

With TCO:

function sumTail(n, acc = 0) { if (n === 0) return acc; return sumTail(n - 1, acc + n); // Tail call — nothing left after the call }
  • The function returns directly from the recursive call → no extra work after → safe for TCO.

  • Only works if JS engine supports it (most don't yet).


3. Easy/Slang Explanation:

Imagine if you’re calling a friend (a function) and right after the call you die (your job is done). That’s a tail call.

Now if you're smart, you tell your boss: “Hey, reuse my desk for the next guy.” That’s Tail Call Optimizationno new memory used, because you're not coming back.

Without TCO: You keep piling phones (stack frames) → boom 💥 stack overflow.

With TCO: One phone gets reused → no boom 😎.


Reality Check:

  • Only Safari supports TCO

  • Chrome, Firefox, Node.js – NO TCO, so you'll still hit stack overflow even if written correctly



5. how async functions affect the stack?

Ans. 

How async Functions Affect the Call Stack – No BS Breakdown


1. Formal Definition + Example:

When an async function is called, it runs synchronously until it hits an await. At that point:

  • It pauses execution, offloads the rest of the code to the microtask queue, and

  • Pops off its execution context from the call stack.

Later, when the awaited promise resolves, the remaining code gets pushed back to the call stack via the event loop.

Example:
async function foo() { console.log("Start"); await Promise.resolve(); // pauses here console.log("End"); } foo(); console.log("Outside");

Output:

Start Outside End

Why?

  • "Start" runs immediately.

  • await pauses the rest → "foo" is popped off the stack.

  • "Outside" runs (still in main thread).

  • "End" runs later, when the microtask queue puts it back.


2. Code + Stack Flow Breakdown:

async function one() { console.log("One"); await two(); console.log("One after await"); } async function two() { console.log("Two"); } one(); console.log("Global End");

Output:

One Two Global End One after await

Stack/Queue Flow:

  1. Global() → pushed

  2. one() called → pushed

  3. console.log("One")

  4. two() called → pushed

  5. console.log("Two")

  6. two() finishes → popped

  7. Hits await → pauses one() here

  8. one() is popped

  9. console.log("Global End")

  10. Promise resolves → console.log("One after await") pushed via microtask queue → runs last


3. Easy/Slang Explanation:

async functions are like chill bros – they start doing their work, but when they hit await, they’re like:

“I’ll wait here. You go ahead. I’ll come back later.”

So they get off the stack, don’t block anything, and when whatever they were waiting for finishes, they come back quietly and finish their job.

This is why async/await is non-blocking, and the call stack stays clean instead of being hogged by long waits.


TL;DR:

🔍 Action📦 What Happens to the Stack?
Call async function        Added to stack like any other function
Hit await        Execution pauses, stack is cleared
Promise resolves        Resumes from await via microtask queue



6. Hoisting?

Ans.

1. Formal Definition + Example:

Hoisting is JavaScript’s default behavior of moving variable and function declarations to the top of their scope (global or function) during the compilation phase, before any code runs.

Only declarations are hoisted — initializations are not.

Example:
console.log(a); // undefined var a = 5;

Internally behaves like:

var a; console.log(a); // undefined a = 5;

2. Code Examples + Explanation:

🧠 Hoisting with var:
console.log(x); // undefined var x = 10;
  • var x is hoisted → initialized with undefined.

  • The assignment x = 10 happens later.


Hoisting with let / const:
console.log(y); // ReferenceError ❗ let y = 20;
  • let and const are also hoisted, but stay in a Temporal Dead Zone (TDZ) until their line is reached → can't access them before declaration.


Function Hoisting:
greet(); // "Hi" function greet() { console.log("Hi"); }
  • Function declarations are fully hoisted – name + body – so you can call them before they appear in code.


⚠️ Function Expression Hoisting:
sayHi(); // TypeError ❗ var sayHi = function () { console.log("Hi"); };
  • sayHi is hoisted as undefined (because it's a var), so calling it before assignment causes TypeError: sayHi is not a function.


3. Easy/Slang Explanation:

Hoisting is like JavaScript saying:

“Let me gather all the declarations first, so I know what exists before I start running anything.”

  • It pulls var and function names to the top.

  • But only var gets a dumb undefined until it's set.

  • let and const are moody — they exist but scream if you touch them early (TDZ rage 😤).

  • Functions declared with function are VIPs — they get in with full access, even before they’re written.


TL;DR

Declaration TypeHoisted?Initialized?Accessible Before Declaration?
var✅ Yes✅ Yes (as undefined)✅ But gives undefined
let / const✅ Yes❌ No (TDZ)❌ ReferenceError
function✅ Yes✅ Yes✅ Fully callable
function expr. (var)✅ Var is, not the function❌ No❌ TypeError
 


7. Scope Chain?

Ans. 

1. Formal Definition + Example:

The Scope Chain is the mechanism JavaScript uses to resolve variable names. When a variable is referenced, JS looks:

  1. In the current/local scope.

  2. If not found, it goes up one level to the outer (parent) scope.

  3. Keeps going until it reaches the global scope.

  4. If still not found → ❌ ReferenceError.

This “chain” of scopes is created lexically — based on where code is written, not called.

Example:
let a = 1; function outer() { let b = 2; function inner() { let c = 3; console.log(a, b, c); // ✅ All accessible } inner(); } outer();

The scope chain here: inner → outer → global.


2. Code Example + Explanation:

🧠 Scope Chain Lookup:
const x = 10; function parent() { const y = 20; function child() { const z = 30; console.log(x + y + z); // 60 } child(); } parent();
  • JS looks for x in child() → not found.

  • Moves to parent() → not found.

  • Moves to global → ✅ found.

  • Same for y, z.

❌ Variable Not in Scope Chain:
function test() { console.log(user); // ❌ ReferenceError } test(); let user = "Faraz";
  • test() is defined before user exists in any outer scope → it can’t see user, even if it’s declared later.


3. Easy/Slang Explanation:

Imagine you're in a room (a function) and need to find a snack (x). First you check your room. Not there? Go to your parent’s room. Still not there? Try the hallway (global).

That’s the Scope Chain — a vertical search path for variables based on where code is written, not where it's called.

JS never looks sideways (sibling scopes). It only looks up the chain.


TL;DR

Scope TypeCan Access
Function Scope        Its own + parent + global
Global Scope        Only its own stuff
No Scope        ReferenceError



8. Closures?

Ans. 

1. Formal Definition + Example:

A closure is formed when a function “remembers” variables from its lexical scope even after the outer function has finished executing.

It gives you access to outer variables even after the outer function is gone.

This is possible because functions in JavaScript carry their scope with them when they are created.

Example:
function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3

count is remembered by inner() even after outer() is done running.


2. Code Example + Breakdown:

🔁 Simple Closure Counter:
function createCounter() { let value = 0; return { increment: () => ++value, decrement: () => --value, }; } const counter = createCounter(); console.log(counter.increment()); // 1 console.log(counter.increment()); // 2 console.log(counter.decrement()); // 1

What’s Happening:

  • value lives in createCounter()’s scope.

  • The returned arrow functions keep a reference to value via closure.

  • Even though createCounter() finishes, value is not garbage collected because it's "closed over."


3. Easy/Slang Explanation:

Closures are like a function having memory.

Imagine you're a waiter (function). When the restaurant (outer function) closes, you still remember your table’s order (count, value, etc.).

You’re carrying that info with you in your brain (closure) — even if the kitchen (outer function) is long gone.

So even outside the restaurant, you can say:

“Hey, table 3 wanted 2 coffees, right?” ☕


TL;DR

🔍 Feature⚙️ Behavior
Keeps variables    ✅ Remembers outer variables
Runs later    ✅ Even after outer is done running
Memory usage    ⚠️ Can cause memory leaks if misused

When You Use Closures:

  • Private variables in JS (module pattern)

  • Callbacks, event handlers

  • setTimeout, setInterval logic

  • Functional programming (currying, memoization)





9. Debouncing of a function in javascript?

Ans.

✅ 1. Formal Definition with Example

Debouncing is a programming technique that ensures a function is only executed after a certain delay — and only onceafter the last time it was invoked.

Used to limit how often a function runs, especially with events like scroll, resize, or input.


✅ 2. Code Example with Explanation

function debounce(func, delay) { let timer; return function (...args) { clearTimeout(timer); // clear previous timer timer = setTimeout(() => { func.apply(this, args); // run function after delay }, delay); }; } // Example: log when user types, but not on every keystroke const logInput = debounce(function (e) { console.log("User typed:", e.target.value); }, 500); document.querySelector("input").addEventListener("input", logInput);

🔍 How It Works:

  • debounce() returns a new function.

  • Each time the returned function runs, it clears the old timeout and sets a new one.

  • So the actual func only runs after the delay with no new events.


✅ 3. Easy/Slang Explanation

Debounce is like saying:
“Wait till the user stops typing for 500ms… then do something.”

So it ignores the fast spam of events and only runs the logic once the user chills.


⚡ Real-World Use Cases

  • Search boxes (to avoid 100s of API calls)

  • Resizing window (expensive layout recalculation)

  • Auto-saving drafts

  • Button click spam prevention






10. 'this' keyword in depth?

Ans. 

1. Formal Definition + Example:

The this keyword in JavaScript refers to the execution context—the object that “owns” the current function.
Its value depends entirely on how a function is called, not where it’s defined.

Example:
const user = { name: "Faraz", greet() { console.log(`Hi, I'm ${this.name}`); } }; user.greet(); // "Hi, I'm Faraz" → `this` refers to `user`

2. Different this Scenarios with Code + Explanation


🧠 Global Context (non-strict mode)
console.log(this); // In browser: `window`
  • In the global scope, this refers to the global object.

  • In the browser: window

  • In Node.js: global


🔒 Strict Mode
"use strict"; function test() { console.log(this); // undefined } test();
  • In strict mode, this inside functions is undefined (not global).


👤 Object Method
const obj = { name: "Faraz", sayHi() { console.log(this.name); } }; obj.sayHi(); // "Faraz" → `this` is `obj`

⚠️ Losing Context (Detached method)
const obj = { name: "Faraz", sayHi() { console.log(this.name); } }; const greet = obj.sayHi; greet(); // undefined (or window.name in sloppy mode)
  • this gets lost because the method is called without context.


this in Arrow Functions
const user = { name: "Faraz", greet: () => { console.log(this.name); } }; user.greet(); // undefined → `this` is **not bound** in arrow functions

✅ Arrow functions don’t have their own this — they inherit it from their lexical scope.


👨‍🔧 Constructor Function
function Person(name) { this.name = name; } const p1 = new Person("Faraz"); console.log(p1.name); // "Faraz"
  • this refers to the newly created object.


🧠 Using call, apply, bind
function show() { console.log(this.name); } const user = { name: "Faraz" }; show.call(user); // "Faraz" show.apply(user); // "Faraz" const bound = show.bind(user); bound(); // "Faraz"
  • call() and apply() set this manually.

  • bind() returns a new function permanently bound to that context.


3. Easy/Slang Explanation

this is just “who called me?”

It’s like:

  • "If your boss (object) calls you, you're working for them (this = boss)."

  • "If nobody calls you (global), you work for the default boss (window/global)."

  • "If you're an arrow function, you’re lazy and just copy your boss’s context."


TL;DR Cheatsheet

Situationthis refers to…
Global (non-strict)  window or global
Global (strict)  undefined
Inside object method    That object
Inside arrow function    Lexical (outer) this
Inside regular function  undefined (strict) / global
Constructor (new)    The new object
With .call() / .apply()    The explicitly passed object
With .bind()    The bound object





11. bind(), call(), and apply() in JavaScript?

Ans. 

1. Formal Definition + Example:

All three methods (bind, call, apply) are used to manipulate the value of this in a function.

MethodWhat it does
call()    Calls the function immediately, sets this
apply()    Like call, but takes arguments as array
bind()    Returns a new function with bound this

2. Code Examples + Explanation:

🧪 Base Setup:
const person = { name: "Faraz", }; function greet(greeting, emoji) { console.log(`${greeting}, I'm ${this.name} ${emoji}`); }

call() – Immediate Execution, args separated
greet.call(person, "Hello", "👋"); // Output: Hello, I'm Faraz 👋
  • First arg is this, rest are normal function arguments.


apply() – Immediate Execution, args as array
greet.apply(person, ["Hi", "😎"]); // Output: Hi, I'm Faraz 😎
  • Same as call() but arguments passed as an array.


bind() – Returns a new function, doesn't run immediately
const sayHi = greet.bind(person, "Hey", "🔥"); sayHi(); // Output: Hey, I'm Faraz 🔥
  • bind() returns a new function where this is locked to person.


3. Easy/Slang Explanation

Think of a function as a homeless guy. These methods give him a job (this) and optionally some supplies (arguments):

  • call(): “Here’s your job and tools — get to work now.”

  • apply(): “Same thing, but I give the tools in a toolbox (array).”

  • bind(): “Here’s your job and tools, but wait till I call you later.”


TL;DR Summary

MethodWhen to UseExecutes Immediately?Args Format
call()Run a function with specific this✅ YesComma-separated
apply()Like call but with arrays✅ YesArray
bind()Create a new function with this❌ NoComma-separated


Real Use Case Example (Event Listener Fix):

const button = document.querySelector("button"); const obj = { name: "Faraz", handleClick() { console.log("Clicked by " + this.name); } }; button.addEventListener("click", obj.handleClick.bind(obj)); // ✅ Fixes `this`



12. Promises & Async/Await?

Ans. 

1. Formal Definition + Example:

Promises are objects representing the eventual completion or failure of an asynchronous operation and its resulting value.

Async/Await is syntactic sugar on top of promises that makes asynchronous code look and behave like synchronous code, making it easier to read and write.


2. Code Examples + Explanation:

🧪 Promise Basics:
const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve("Success!"); }, 1000); }); myPromise.then(result => { console.log(result); // "Success!" after 1 second }).catch(error => { console.error(error); });
  • Promise starts in pending state.

  • After 1 second, it resolves with "Success!".

  • .then() handles success; .catch() handles errors.


🧪 Async/Await Syntax:
function waitOneSecond() { return new Promise(resolve => setTimeout(() => resolve("Done!"), 1000)); } async function asyncFunc() { console.log("Start"); const result = await waitOneSecond(); // pauses here console.log(result); // "Done!" console.log("End"); } asyncFunc();
  • async marks the function as asynchronous.

  • await pauses execution until the promise resolves.

  • Makes async code read top-to-bottom, like sync code.


3. Easy/Slang Explanation:

Promises are like a promise in real life:

“I promise I’ll get back to you with the result.”
You can wait patiently (then), or prepare for disappointment (catch).

Async/Await is just saying:

“Hey, wait here for the promise to keep its word, then continue.”
No messy .then() chaining — just clean, readable code.


TL;DR

ConceptDescriptionSyntax Example
Promise    Represents future value/error    new Promise((res, rej) => {...})
.then()    Handles fulfilled promise    promise.then(val => ...)
.catch()    Handles rejected promise    promise.catch(err => ...)
async    Marks function as async    async function foo() {...}
await    Pauses function until promise resolves    const val = await promise

When to Use What?

  • Use Promises if you want a more explicit chain or work without async/await support.

  • Use Async/Await to write cleaner, more maintainable async code.

  • Remember: await only works inside async functions.



13. Event Loop, Microtasks vs Macrotasks?

Ans. 

1. Formal Definition + Overview:

The Event Loop is the mechanism that allows JavaScript (which is single-threaded) to perform non-blocking asynchronous operations by coordinating the execution of tasks.

  • Call Stack: Where your functions get executed.

  • Task Queues: Where async tasks wait to get onto the call stack.

There are two main types of task queues:

  • Macrotasks (Task Queue)

  • Microtasks (Microtask Queue)


2. Microtasks vs Macrotasks:

FeatureMicrotasksMacrotasks
ExamplesPromise.then(), MutationObserversetTimeout(), setInterval(), I/O
PriorityHigher priority — executed before rendering and macrotasksLower priority — executed after microtasks and rendering
When they runAfter the current stack is empty, but before the browser repaintsAfter microtasks and rendering, picked from the task queue
Runs repeatedlyRuns until microtask queue is emptyOne macrotask per event loop tick

3. Event Loop Flow (Simplified):

  1. Run all synchronous code (call stack empties).

  2. Run all microtasks (e.g., promise callbacks).

  3. Render UI (if needed).

  4. Run one macrotask (e.g., setTimeout callback).

  5. Repeat.


4. Code Example + Explanation:

console.log("Script start"); setTimeout(() => { console.log("setTimeout macrotask"); }, 0); Promise.resolve().then(() => { console.log("Promise microtask"); }); console.log("Script end");

Output:

Script start Script end Promise microtask setTimeout macrotask
  • Synchronous logs run first.

  • Promise .then callback runs next (microtask).

  • setTimeout callback runs last (macrotask).


5. Easy/Slang Explanation:

Imagine a nightclub:

  • Call Stack is the bartender serving customers (functions).

  • Microtasks are the VIP guests who get served right after the current customer finishes, no waiting.

  • Macrotasks are the regular customers who have to wait their turn after VIPs are done.

  • The bartender keeps serving until everyone’s done.

Promises and mutation observers are VIPs; timers and I/O events are regulars.


TL;DR Summary

Queue TypePriorityExamplesWhen executed
MicrotasksHighPromises, MutationObserverRight after current execution stack empties, before rendering
MacrotasksLowsetTimeout, I/O, UI eventsAfter microtasks and rendering



14. setTimeout and setInterval?

Ans. 

1. Formal Definition + Example:

  • setTimeout(fn, delay): Schedules a function fn to run once after at least delay milliseconds.

  • setInterval(fn, delay): Schedules a function fn to run repeatedly every delay milliseconds until cleared.


2. Code Examples + Explanation:

setTimeout – Run Once After Delay
console.log("Before timeout"); setTimeout(() => { console.log("Executed after 2 seconds"); }, 2000); console.log("After timeout");

Output:

Before timeout After timeout Executed after 2 seconds
  • The callback runs after synchronous code finishes and after approx 2 seconds.


setInterval – Run Repeatedly
let count = 0; const intervalId = setInterval(() => { console.log("Interval count:", ++count); if (count === 3) { clearInterval(intervalId); // stop after 3 times } }, 1000);
  • The callback runs every 1 second until clearInterval is called.


3. How They Work Internally:

  • Both use the browser’s timer APIs (or Node.js timers).

  • When the timer expires, the callback is put into the macrotask queue.

  • The event loop runs the callback after the current stack and microtasks finish.

  • Delays are minimum delays — actual execution might be later due to queue congestion.


4. Common Gotchas:

  • Minimum delay: Browsers enforce a minimum delay (usually 4ms for nested timers).

  • setTimeout(fn, 0) doesn’t run immediately — it schedules the callback as a macrotask.

  • setInterval callbacks can pile up if the callback takes longer than the interval.

  • Use clearTimeout and clearInterval to avoid memory leaks and unwanted calls.


5. Easy/Slang Explanation:

Think of:

  • setTimeout as:

    “Hey, remind me to do this once after X minutes.”
    Like setting an alarm clock for one-time wake-up.

  • setInterval as:

    “Hey, remind me to do this again and again every X minutes.”
    Like an annoying alarm that rings repeatedly till you turn it off.


TL;DR

Function    Runs how often?When executed?    Cancel with
setTimeout    OnceAfter delay + event loop wait    clearTimeout(id)
setInterval    RepeatedlyEvery delay + event loop wait    clearInterval(id)




15. Debounce & Throttle?

Ans. 

1. Formal Definition + Purpose:

  • Debounce: Ensures a function is only called after a certain delay has passed without it being called again. Useful to limit how often a function fires after events stop happening.

  • Throttle: Ensures a function is called at most once every specified time interval, no matter how many times the event fires. Useful to limit how often a function fires during continuous events.


2. Code Examples + Explanation:

🔥 Debounce Example (wait till event stops firing)
function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } // Usage: window.addEventListener("resize", debounce(() => { console.log("Resize event handled after user stopped resizing."); }, 300));
  • The function runs only after 300ms of no resize event.

  • If events keep firing, it keeps postponing execution.


⚡ Throttle Example (limit calls to once every interval)
function throttle(fn, limit) { let lastCall = 0; return function (...args) { const now = Date.now(); if (now - lastCall >= limit) { lastCall = now; fn.apply(this, args); } }; } // Usage: window.addEventListener("scroll", throttle(() => { console.log("Scroll event handled at most once every 500ms."); }, 500));
  • The function runs immediately on first call.

  • Then blocks calls until 500ms passed.

  • Useful for events that fire rapidly like scrolling.


3. Easy/Slang Explanation:

  • Debounce:

“Stop shouting at me! I’ll only listen when you pause for a moment.”
Perfect for search inputs or resize events where you want to react after the user stops typing or resizing.

  • Throttle:

“Chill out, I’ll listen to you once in a while no matter how loud you get.”
Great for scroll or mousemove events where you want regular updates but not too many.


TL;DR Summary

TechniqueWhen to UseHow it Works
DebounceAfter event stops firingDelays call until event quiet for delay
ThrottleLimit how often during eventCalls immediately, then blocks calls till limit time passed





16. JavaScript Modules (import/export)?

Ans. 

1. Formal Definition + Example:

Modules allow you to split your code into separate files and reuse code by importing/exporting functions, objects, or primitives.

  • export makes something available to other files.

  • import brings those exported things into another file.

Modern JS modules use the ES6 module syntax (import/export).


2. Code Examples + Explanation:

Named Exports & Imports

math.js

export function add(a, b) { return a + b; } export const PI = 3.14159;

app.js

import { add, PI } from './math.js'; console.log(add(2, 3)); // 5 console.log(PI); // 3.14159
  • You export multiple named things.

  • Import with curly braces matching the names.


Default Export & Import

logger.js

export default function log(message) { console.log(message); }

app.js

import log from './logger.js'; log("Hello"); // prints "Hello"
  • Default export means you import without {} and can rename as you want.


Renaming Imports/Exports
// math.js export { add as sum }; // app.js import { sum } from './math.js';

3. Easy/Slang Explanation:

Modules are like packages of code you can send around.

  • export = “Here’s what I’m sharing.”

  • import = “I want to use that stuff in my file.”

You can share named things (like named gifts) or a default thing (like the main gift).


TL;DR

FeatureSyntaxNotes
Named export    export function foo() {}    Import with { foo }
Named import    import { foo } from './file'    Exact names, can rename
Default export    export default function foo() {}    Import without {}, rename allowed
Renaming    export { foo as bar }  import { bar }






17. Error Handling in JavaScript (try/catch/finally)?

Ans. 

1. Formal Definition + Example:

try/catch/finally is a control structure to handle runtime errors gracefully without crashing your program.

  • try: Wrap code that might throw an error.

  • catch: Run if an error occurs inside try.

  • finally: Always runs after try and catch (whether error occurred or not).


2. Code Examples + Explanation:

try { // risky code here let result = riskyFunction(); console.log(result); } catch (error) { // handle error here console.error("Caught error:", error.message); } finally { // always runs console.log("Cleanup or final steps."); }
  • If riskyFunction() throws, code jumps to catch.

  • finally runs always, even if no error or if error was thrown.


3. Easy/Slang Explanation:

Think of it like a try-catch block in real life:

  • Try: You try to do something (like driving).

  • Catch: If something goes wrong (like a flat tire), catch lets you handle it (call for help).

  • Finally: Cleanup happens no matter what (putting your car in the garage).


TL;DR

BlockPurpose
try    Code that might fail
catch    Handle error if try fails
finally    Run code always, cleanup or final steps

Bonus: Throwing Your Own Errors

function divide(a, b) { if (b === 0) throw new Error("Division by zero!"); return a / b; } try { divide(5, 0); } catch (e) { console.error(e.message); // "Division by zero!" }



18. JSON & Fetch API?

Ans. 

1. Formal Definition + Example:

  • JSON (JavaScript Object Notation) is a lightweight, text-based format to store and exchange data. It looks like JS objects but is actually a string.

  • Fetch API is a modern browser API to make network requests (like GET, POST) returning Promises.


2. JSON Basics:

const obj = { name: "Faraz", age: 25 }; // Convert JS object to JSON string const jsonStr = JSON.stringify(obj); // Output - {"name":"Faraz","age":25} // Convert JSON string back to JS object const parsedObj = JSON.parse(jsonStr); // Output - { name: 'Faraz', age: 25 }

  • Use JSON.stringify() to send data over the network.

  • Use JSON.parse() to convert received JSON string back to JS objects.


3. Fetch API Example (GET request):

fetch('https://api.example.com/data') .then(response => { if (!response.ok) throw new Error('Network error'); return response.json(); // parse JSON body }) .then(data => { console.log(data); // Use data here }) .catch(error => { console.error('Fetch error:', error); });
  • fetch() returns a Promise with the response.

  • Call .json() to parse JSON body (also returns Promise).


4. Fetch API Example (POST request):

fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Faraz', age: 25 }), }) .then(res => res.json()) .then(data => console.log('Response:', data)) .catch(err => console.error('Error:', err));
  • Use method to specify HTTP method.

  • Use headers to specify content type.

  • Use body with JSON.stringify() for sending JSON.


5. Easy/Slang Explanation:

  • JSON:

"It's just text that looks like JS stuff so computers can send info back and forth."

  • Fetch:

"It's like ordering food from a restaurant (server). You say what you want (request), and when it’s ready, they bring it back (response)."


TL;DR

ConceptWhat it doesExample Function
JSON    Format for data exchange    JSON.stringify(), JSON.parse()
Fetch API    Makes HTTP requests, returns Promise    fetch(url).then(...).catch(...)




















-------------------------------------------------------------------------------------------------

⚙️ Phase 4: OOP + Functional Programming in JS 


1. Constructor Functions in JavaScript?

Ans. 

1. Formal Definition + Example:

A constructor function is a regular function used to create multiple similar objects. When called with the new keyword, it creates a new object, sets this to that object, and returns it.


function Person(name, age) { this.name = name; this.age = age; this.sayHi = function () { console.log(`Hi, I'm ${this.name}`); }; } const user1 = new Person("Faraz", 22); user1.sayHi(); // Hi, I'm Faraz

2. What Happens Internally with new:

When you do new Person("Faraz", 22):

  1. A new empty object is created: {}

  2. this is set to that object inside the function

  3. Properties/methods are added to this

  4. The object is returned automatically


3. Prototype Optimization (Good Practice):

Instead of defining functions inside the constructor (wasteful), put them on the prototype:

function Person(name, age) { this.name = name; this.age = age; } Person.prototype.sayHi = function () { console.log(`Hi, I'm ${this.name}`); }; const user2 = new Person("Aditya", 23); user2.sayHi(); // Hi, I'm Aditya

Now all Person instances share one sayHi function, saving memory.


4. Slang / Easy Explanation:

"Constructor functions are like cookie cutters 🍪. You define the shape (Person), then use it with new to punch out multiple cookies (objects) with different toppings (data)."


⚠️ Notes:

  • Always capitalize constructor function names by convention (like Person, Car, etc.)

  • Don't forget to use new. If you call it without new, this becomes undefined or global object (bad).




2. Prototypes & Prototype Chain in JavaScript?

Ans. 

1. Formal Definition + Example

  • Every object in JavaScript has an internal property called [[Prototype]] (or __proto__), which points to another object.

  • That "other object" is the prototype from which it can inherit properties and methods.

  • This chain of inheritance is called the Prototype Chain.

Example:
const person = { greet: function () { console.log("Hello"); }, }; const student = { name: "Faraz", }; student.__proto__ = person; student.greet(); // "Hello"

Here, student doesn't have greet(), so JavaScript looks up the prototype chain and finds it in person.


2. Prototype Chain

When you try to access a property:

  • JS first looks in the object itself.

  • If not found, it checks __proto__ (its prototype).

  • This continues up the chain until it hits null.


student → person → Object.prototype → null

3. Function Prototypes

Every function in JS has a prototype property which is used when that function is used as a constructor.

function Animal() {} Animal.prototype.eat = function () { console.log("Eating"); }; const dog = new Animal(); dog.eat(); // Inherited from Animal.prototype

4. Slang / Easy Explanation

Think of prototypes like a backup plan:
“If I don’t have it, I’ll ask my parent (prototype). If they don’t have it, they’ll ask their parent... until we run out of parents.”


5. Prototype vs proto

prototype__proto__
Property on functionsProperty on objects
Used to build __proto__Points to the function's prototype
Used during constructionUsed during lookup

6. Visual

function Person() { this.name = "Faraz"; } Person.prototype.sayHi = function () { console.log("Hi"); }; const p = new Person(); console.log(p.__proto__ === Person.prototype); // true console.log(Person.prototype.__proto__ === Object.prototype); // true



3. ES6 Classes?

Ans. 

1. Formal Definition + Example

  • ES6 class is syntactic sugar over JavaScript's prototypal inheritance.

  • It provides a cleaner, more familiar OOP-style syntax (like in Java, C++, Python) to create constructor functions and manage prototypes.

✅ Example:
class Person { constructor(name) { this.name = name; } greet() { console.log(`Hello, I am ${this.name}`); } } const faraz = new Person("Faraz"); faraz.greet(); // "Hello, I am Faraz"

Under the hood, Person is still a function, and greet() lives on Person.prototype.


2. Class Inheritance

class Student extends Person { constructor(name, course) { super(name); // calls the parent class constructor this.course = course; } info() { console.log(`${this.name} studies ${this.course}`); } } const s = new Student("Faraz", "CSE"); s.greet(); // from Person s.info(); // from Student

3. Easy/Slang Explanation

Classes in JS are just nicer wrappers over how prototypes work.
Instead of saying function Dog() {}, you now say class Dog {} — same game, new skin.


4. Key Features

FeatureDescription
constructor()    Called automatically when a new object is created
extends    Used for inheritance
super()    Calls the parent constructor
Class Methods    Defined directly inside the class
Static Methods    Bound to class, not instances (static methodName())
Getters/Setters    Define properties with get and set keywords

5. Static Methods

class MathUtils { static add(x, y) { return x + y; } } console.log(MathUtils.add(2, 3)); // 5

6. Behind the Scenes

typeof Person; // 'function' faraz instanceof Person; // true Object.getPrototypeOf(faraz) === Person.prototype; // true

So even class is just a function constructor, but in a cleaner way.





4. Inheritance in JS?

Ans. 

1. Formal Definition + Example

Inheritance in JavaScript is the mechanism by which one object can access properties and methods of another. It’s prototypal, not class-based (like Java/C++), though ES6 class syntax mimics class-based inheritance.

✅ Example (Pre-ES6 using Prototypes):
function Animal(name) { this.name = name; } Animal.prototype.speak = function () { console.log(`${this.name} makes a sound`); }; function Dog(name, breed) { Animal.call(this, name); // Inherit constructor this.breed = breed; } Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; Dog.prototype.bark = function () { console.log(`${this.name} barks`); }; const tommy = new Dog("Tommy", "Lab"); tommy.speak(); // Tommy makes a sound tommy.bark(); // Tommy barks

2. Modern ES6+ Class Inheritance

class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound`); } } class Dog extends Animal { constructor(name, breed) { super(name); // call parent constructor this.breed = breed; } bark() { console.log(`${this.name} barks loudly`); } } const max = new Dog("Max", "Beagle"); max.speak(); // Max makes a sound max.bark(); // Max barks loudly

3. Easy/Slang Explanation

JavaScript lets one object “borrow” stuff from another.
Old school? You clone objects via the prototype chain.
New school? You just write extends and use super() like in other languages.


4. Under the Hood – Prototype Chain

console.log(max instanceof Dog); // true console.log(max instanceof Animal); // true
  • Dog.prototype links to Animal.prototype

  • max.__proto__Dog.prototype

  • Dog.prototype.__proto__Animal.prototype

That's the chain.


5. Key Concepts

ConceptMeaning
super()    Calls the parent class constructor or method
extends    Establishes prototype link between classes
Object.create()    Manual prototype inheritance
__proto__    Actual link to the prototype chain
prototype    Where inherited methods live




5. Encapsulation and Abstraction?

Ans. 

1. Formal Definitions + Example

Encapsulation

Encapsulation is the bundling of data (variables) and methods (functions) into a single unit (object), and restricting direct access to some of the object’s components.

Abstraction

Abstraction means hiding complex logic and exposing only the necessary parts to the user—focus on what an object does, not how it does it.


2. Code Example with Explanation (Using Classes)

class BankAccount { #balance = 0; // private field (ES2022) constructor(owner) { this.owner = owner; } deposit(amount) { if (amount > 0) { this.#balance += amount; } } withdraw(amount) { if (amount <= this.#balance) { this.#balance -= amount; } else { console.log("Insufficient funds"); } } getBalance() { return this.#balance; } } const acc = new BankAccount("Faraz"); acc.deposit(5000); acc.withdraw(1000); console.log(acc.getBalance()); // 4000 console.log(acc.#balance); // ❌ SyntaxError: Private field

📌 Explanation:

  • #balance is encapsulated: cannot be accessed directly.

  • Methods like deposit, withdraw, and getBalance abstract the internal working.

  • This hides how balance is stored or updated, and allows users to interact only through a safe API.


3. Slang/Easy Explanation

  • Encapsulation is like keeping your data in a locked box—others can only use buttons you provide.

  • Abstraction is like using a car—you turn the key and drive, without worrying about how the engine works.


4. Without ES6 Classes – Still Possible

function createUser(name) { let password = "secret"; // private via closure return { getName() { return name; }, checkPassword(pw) { return pw === password; } }; } const user = createUser("Faraz"); console.log(user.getName()); // Faraz console.log(user.checkPassword("secret")); // true console.log(user.password); // undefined (private)

✅ This is closure-based encapsulation & abstraction in functional style.





6. Factory Functions vs Constructor?

Ans. 

🔹 1. Formal Definitions + Example

Factory Function

A function that returns a new object without using new. It creates and returns an object explicitly.

Constructor Function

A function intended to be used with the new keyword to construct and initialize new object instances.


🔹 2. Code Comparison with Explanation

🏭 Factory Function

function createUser(name, age) { return { name, age, greet() { console.log(`Hi, I'm ${this.name}`); } }; } const user1 = createUser("Faraz", 22); user1.greet(); // Hi, I'm Faraz

👷‍♂️ Constructor Function

function User(name, age) { this.name = name; this.age = age; this.greet = function () { console.log(`Hi, I'm ${this.name}`); }; } const user2 = new User("Faraz", 22); user2.greet(); // Hi, I'm Faraz

🔹 3. Slang/Easy Explanation

  • Factory function: Like a blue-collar factory—you call it and it spits out a new customized object.

  • Constructor function: Like using new to hire a worker (object) and initialize them with this.


🔹 4. Pros/Cons Table

FeatureFactory FunctionConstructor Function
new keyword needed❌ No✅ Yes
this keyword used❌ Optional✅ Required
Inheritance with Object.create()✅ Yes✅ With prototype
Can use private variables✅ Easily via closures❌ Not natively (before ES2022)
More readable/flexible✅ Often❌ Slightly more rigid
Used in modern JS/React✅ Very common🔄 Still used sometimes

🔹 5. When to Use What?

Use Case    Recommended
Need private variables    Factory
Want object-oriented inheritance via new    Constructor
Cleaner syntax / functional programming    Factory
Simpler debugging with stack traces    Constructor

🔹 6. Bonus: Using Prototypes (for memory efficiency)

// Constructor with prototype
function User(name) { this.name = name; } User.prototype.greet = function () { console.log(`Hello from ${this.name}`); };

// Factory with shared methods const userProto = { greet() { console.log(`Hello from ${this.name}`); } }; function createUser(name) { return Object.create(userProto, { name: { value: name, enumerable: true } }); }



7. Composition over Inheritance?

Ans. 

🔹 1. Formal Definition + Example

Composition over inheritance is a design principle that favors combining simple, independent behaviors (composition) instead of using deep and rigid class hierarchies (inheritance).

✅ It promotes code reuse by mixing behaviors, not by inheriting them.


🔹 2. Code Example + Explanation

❌ Inheritance Example (Tight coupling)

class Animal { eat() { console.log("Eating..."); } } class Dog extends Animal { bark() { console.log("Barking..."); } } const dog = new Dog(); dog.eat(); // Eating... dog.bark(); // Barking...

✅ Composition Example (Loose coupling)

const canEat = (state) => ({ eat: () => console.log(`${state.name} is eating`) }); const canBark = (state) => ({ bark: () => console.log(`${state.name} is barking`) }); function createDog(name) { const state = { name }; return Object.assign({}, canEat(state), canBark(state)); } const dog = createDog("Bruno"); dog.eat(); // Bruno is eating dog.bark(); // Bruno is barking

🔹 3. Slang/Easy Explanation

  • Inheritance = "I am a thing"

    • e.g., A Dog is-an Animal

  • Composition = "I have abilities"

    • e.g., A Dog has the ability to eat and bark

Instead of one big class doing everything, break features into small reusable pieces you can plug into objects.


🔹 4. Why Composition > Inheritance?

✅ Composition❌ Inheritance
More flexible & reusableRigid & tightly coupled
Easy to test and isolate behaviorsHarder to test deep hierarchies
Encourages separation of concernsInheritance can lead to God objects
Works better in JS (prototype-based language)Mimics class-based OOP (less idiomatic JS)

🔹 5. When Should You Use Composition?

  • When behavior needs to be shared across different objects

  • When you want to avoid fragile base class problems

  • When you need multiple behaviors without deep inheritance trees


🔹 6. BONUS: Reusable Behaviors with Composition

const canFly = (state) => ({ fly: () => console.log(`${state.name} is flying!`) }); const canSwim = (state) => ({ swim: () => console.log(`${state.name} is swimming!`) }); function createDuck(name) { const state = { name }; return Object.assign({}, canFly(state), canSwim(state)); } const daffy = createDuck("Daffy"); daffy.fly(); // Daffy is flying! daffy.swim(); // Daffy is swimming!



7. Pure Functions and Immutability?

Ans. 

🔹 1. Formal Definition + Example

Pure Function

A pure function is a function that:

  • Always returns the same output for the same input.

  • Does not cause side effects (like modifying global variables, DOM, or doing I/O).

Example:

function add(a, b) { return a + b; }

🚫 Impure Function (side effect):

let count = 0; function increment() { count++; }

Immutability

Immutability means data cannot be changed once created. Instead, you create and work with copies of data.

Example:

const arr = [1, 2, 3]; const newArr = [...arr, 4]; // arr remains unchanged

🔹 2. Code Example + Explanation

✅ Pure + Immutable Example:

function addToCart(cart, item) { return [...cart, item]; // returns new array } const cart = ['Apple']; const newCart = addToCart(cart, 'Banana'); console.log(cart); // ['Apple'] — original remains console.log(newCart); // ['Apple', 'Banana']

🔹 3. Slang/Easy Explanation

  • Pure function = "Like a vending machine: input coin + code → same snack every time, no weird behavior."

  • Immutable = "Don't touch the original stuff; copy and change the copy."


🔹 4. Why It Matters

ConceptWhy it’s 🔥 Useful
Pure FunctionsEasy to test, debug, and reuse
ImmutabilityPrevents accidental bugs, makes code safer

🔹 5. Real-World Usage (React-friendly)

React promotes both:

// React reducer example function counter(state, action) { if (action.type === 'increment') { return { ...state, count: state.count + 1 }; } return state; }

✅ Pure
✅ Immutable
✅ Predictable behavior




8. Currying vs Partial Application in JavaScript?

Ans. 

🔹 1. Formal Definitions + Examples

Currying

Currying is the process of transforming a function with multiple arguments into a sequence of functions, each taking a single argument.

Example:

function add(a) { return function(b) { return a + b; }; } const add5 = add(5); console.log(add5(3)); // 8

With arrow functions:

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

Partial Application

Partial application is when you fix some arguments of a function, creating a new function with fewer parameters.

Example:

function multiply(a, b, c) { return a * b * c; } function partialMultiplyBy2(b, c) { return multiply(2, b, c); } console.log(partialMultiplyBy2(3, 4)); // 24

Or with .bind():

const multiplyBy2 = multiply.bind(null, 2); console.log(multiplyBy2(3, 4)); // 24

🔹 2. Key Differences

FeatureCurryingPartial Application
TransformationConverts to unary functionsFixes some arguments
Return typeSeries of single-arg functionsNew function with fewer args
FocusAll args separatedPre-filling some args

🔹 3. Slang/Easy Explanation

  • Currying: “One spoon at a time” – You give one input, get one spoonful function back.

  • Partial Application: “Pre-fill the form” – You give some info upfront and finish the rest later.


🔹 4. Use Case Example

Currying with config:

const greet = greeting => name => `${greeting}, ${name}`; const sayHi = greet('Hi'); console.log(sayHi('Faraz')); // Hi, Faraz

Partial Application for logging:

function log(level, message) { console.log(`[${level}] ${message}`); } const logError = log.bind(null, 'ERROR'); logError('Something went wrong'); // [ERROR] Something went wrong
















-----------------------------------------------------------------------------------------------------

🌐 Phase 5: Browser APIs & Environment 



1. Local Storage?

Ans. 

1. Formal Definition & Example

Local Storage is part of the Web Storage API that enables web applications to store data locally within the user's browser with no expiration date.

✅ Example:

// Store localStorage.setItem('username', 'faraz'); // Retrieve const user = localStorage.getItem('username'); // 'faraz' // Remove localStorage.removeItem('username'); // Clear all localStorage.clear();

2. Code Example with Explanation

// Saving user preferences localStorage.setItem('theme', 'dark'); // Getting the value later const theme = localStorage.getItem('theme'); // returns 'dark' // Deleting specific item localStorage.removeItem('theme'); // Wiping everything from localStorage localStorage.clear();
  • setItem(key, value): Stores a string value.

  • getItem(key): Retrieves the string.

  • removeItem(key): Deletes that key.

  • clear(): Deletes all keys.

🔒 All data is stored as strings. Use JSON.stringify() and JSON.parse() for storing objects:

const user = { name: 'Faraz', age: 21 }; localStorage.setItem('user', JSON.stringify(user)); const retrieved = JSON.parse(localStorage.getItem('user'));

3. Easy/Slang Explanation

Think of localStorage like your browser’s notebook. You can write stuff into it (like user login info, preferences, or theme), and it’ll stay there forever unless you erase it — even if the user closes or refreshes the browser.

It’s super helpful for keeping things like:

  • “Remember me” login

  • Dark mode toggle

  • Cart items in an eCommerce app




2. Session Storage?

Ans. 

 1. Formal Definition & Example

Session Storage is part of the Web Storage API that stores data for the duration of a page session — it gets cleared when the browser tab is closed.

✅ Example:

// Store data sessionStorage.setItem('token', 'abc123'); // Retrieve data const token = sessionStorage.getItem('token'); // Remove data sessionStorage.removeItem('token'); // Clear all sessionStorage.clear();

2. Code Example with Explanation


// Saving login state during one session sessionStorage.setItem('isLoggedIn', 'true'); // Reading it const loginState = sessionStorage.getItem('isLoggedIn'); // 'true' // Deleting one item sessionStorage.removeItem('isLoggedIn'); // Clearing entire session storage sessionStorage.clear();

🧠 Like localStorage, it only stores strings — use JSON.stringify() / JSON.parse() for objects:

const cart = { items: ['book', 'pen'] }; sessionStorage.setItem('cart', JSON.stringify(cart)); const cartData = JSON.parse(sessionStorage.getItem('cart'));

3. Easy/Slang Explanation

Think of sessionStorage like a whiteboard in a browser tab — you can write on it while the tab is open. But as soon as you close the tab, boom 💥, it's wiped.

Use it for:

  • Temporary login tokens

  • Current page filters

  • Unsaved form data


Quick Comparison:

FeaturelocalStoragesessionStorage
Lifespan    Until manually cleared    Until tab is closed
Accessible by    All tabs from same origin    Only in the same tab
Storage Limit    ~5-10 MB    ~5 MB
Use case    Themes, user preferences    Temp auth, one-time data



3. Cookies?

Ans. 

 1. Formal Definition & Example

Cookies are small key-value data pieces stored in the browser and sent automatically to the server with every HTTP request. They can be used for authentication, session management, and tracking.

✅ Example:

// Set a cookie document.cookie = "username=faraz; expires=Fri, 01 Aug 2025 12:00:00 UTC; path=/"; // Read all cookies console.log(document.cookie); // "username=faraz"

2. Code Example with Explanation

// Set a cookie (key=value) document.cookie = "theme=dark; path=/"; // Set with expiration document.cookie = "token=abc123; expires=Fri, 01 Aug 2025 12:00:00 UTC; path=/"; // Read all cookies console.log(document.cookie); // e.g., "theme=dark; token=abc123"
  • document.cookie lets you read/write cookies.

  • Each cookie is a single string key=value, and multiple cookies are separated by ;.

  • Cookies must be manually parsed if you want to extract one value.

🧠 Cookies are sent automatically to the server with every request — unlike localStorage or sessionStorage.


3. Easy/Slang Explanation

Cookies are like tiny stickers that your website puts in your browser. Every time you go back to that website, your browser hands over all the stickers (cookies) to the server. That’s how websites "remember" you.

Used for:

  • Login sessions (auth tokens)

  • Tracking users (analytics)

  • "Remember me" functionality


⚔️ Quick Comparison Table

FeatureCookieslocalStoragesessionStorage
Sent to server    ✅ Yes (with each request)    ❌ No    ❌ No
Expiration    Can be set manually    Never (until cleared)    On tab close
Storage Limit    ~4 KB        ~5-10 MB    ~5 MB
Accessibility    Both server + client    Client only    Client only




4. Navigator API?

Ans. 

1. Formal Definition & Example

The Navigator API is part of the browser’s window.navigator object. It provides information about the browser, operating system, user's device, and capabilities like geolocation, online status, and user agent detection.

✅ Example:

console.log(navigator.userAgent); console.log(navigator.language);

2. Code Examples with Explanation

Basic Info

console.log(navigator.appName); // e.g. 'Netscape' (not useful today) console.log(navigator.userAgent); // Full browser/OS info string console.log(navigator.language); // 'en-US' console.log(navigator.platform); // 'Win32', 'Linux x86_64', etc.

Check if Online

if (navigator.onLine) { console.log("You're online!"); } else { console.log("You're offline!"); }

Geolocation (with permission)

navigator.geolocation.getCurrentPosition( (position) => { console.log(position.coords.latitude, position.coords.longitude); }, (err) => { console.error('Permission denied or error', err); } );

Clipboard API

navigator.clipboard.writeText("Copied to clipboard!");

3. Easy/Slang Explanation

The navigator object is your browser's selfie — it tells JS what kind of browser, OS, and even language you're using. It can also track your location, check if you're online, and access cool features like the clipboard.


✅ Common Use Cases

FeatureCode Sample
Get browser info    navigator.userAgent
Detect platform    navigator.platform
Check online status    navigator.onLine
Get location    navigator.geolocation.getCurrentPosition()
Clipboard access    navigator.clipboard.writeText()
Language detection    navigator.language




5. Geolocation API?

Ans. 

1. Formal Definition & Example

The Geolocation API allows web applications to access the geographic location (latitude and longitude) of a user's device — with the user's explicit permission.

✅ Example:

navigator.geolocation.getCurrentPosition( (position) => { console.log(position.coords.latitude, position.coords.longitude); }, (error) => { console.error('Location error:', error.message); } );

2. Code Example with Explanation

Basic Usage

if ('geolocation' in navigator) { navigator.geolocation.getCurrentPosition( (pos) => { const { latitude, longitude } = pos.coords; console.log(`Lat: ${latitude}, Lon: ${longitude}`); }, (err) => { console.warn(`ERROR(${err.code}): ${err.message}`); } ); } else { console.log("Geolocation not supported"); }

Options (Accuracy, Timeout, Max Age)

const options = { enableHighAccuracy: true, // use GPS if possible timeout: 5000, // max wait time in ms maximumAge: 0 // don't use cached position }; navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);

Watch Position (Track Movement)

const watchId = navigator.geolocation.watchPosition((pos) => { console.log(`Updated position: ${pos.coords.latitude}, ${pos.coords.longitude}`); }); // To stop tracking navigator.geolocation.clearWatch(watchId);

3. Easy/Slang Explanation

The Geolocation API is like GPS for your browser. It asks the user:

“Yo, can I know where you are?”

If the user says yes, you get their current latitude & longitude.

Great for:

  • Weather apps 🌦️

  • Ride tracking 🚗

  • Store locators 🛍️

  • Geo-fencing apps 🗺️


⚠️ Important Notes:

  • Works only over HTTPS (except on localhost).

  • User must grant permission.

  • Accuracy varies (mobile is better than desktop).





6. Clipboard API?

Ans. 

1. Formal Definition & Example

The Clipboard API provides read and write access to the system clipboard. It allows web apps to copy text to or paste text from the clipboard, but only with user interaction or permission.

✅ Example:

navigator.clipboard.writeText("Copied text!");

2. Code Examples with Explanation

Copy to Clipboard

const text = "Hello Faraz!"; navigator.clipboard.writeText(text) .then(() => { console.log("Text copied to clipboard"); }) .catch((err) => { console.error("Failed to copy:", err); });

Paste from Clipboard

navigator.clipboard.readText() .then((text) => { console.log("Pasted text:", text); }) .catch((err) => { console.error("Failed to read clipboard:", err); });

3. Easy/Slang Explanation

Clipboard API is like your browser’s copy-paste tool:

  • writeText() = JS does a Ctrl+C

  • readText() = JS does a Ctrl+V

But for security:

  • Needs user interaction (like a button click).

  • Works only over HTTPS.


🔐 Limitations

  • Won’t work in older browsers.

  • navigator.clipboard is undefined in non-secure contexts.

  • Might need permissions (clipboard-read, clipboard-write).


✅ Real Use Cases

Use CaseCode
Copy coupon codeclipboard.writeText(code)
Paste note contentclipboard.readText()
Share links easilyclipboard.writeText(window.location)
Copy code blocksButton triggers clipboard.writeText()




7. History API?

Ans. 

 1. Formal Definition & Example

The History API allows you to interact with the browser's session history — i.e., pages the user has visited in the current tab. You can navigate, push, or manipulate URLs without reloading the page (crucial for SPAs).

✅ Example:

history.pushState({ page: 1 }, "title 1", "?page=1");

2. Code Examples with Explanation

Push a New State (Change URL without Reload)

history.pushState({ user: 'faraz' }, 'Profile Page', '/profile');
  • Adds a new entry to the browser history stack.

  • Doesn’t reload the page — just changes the URL.

Replace Current State

history.replaceState({ user: 'faraz' }, 'Profile Page', '/profile');
  • Replaces the current entry instead of adding a new one.

Listen for Navigation (Back/Forward)

window.addEventListener('popstate', (event) => { console.log('Back or forward clicked', event.state); });

Navigate Manually

history.back(); // Go back one page history.forward(); // Go forward one page history.go(-2); // Go two pages back

3. Easy/Slang Explanation

The History API is how JavaScript messes with the browser's back and forward buttons without reloading the page.

It’s how SPAs (like React apps) change the URL when switching views — without refreshing.

Think of it like:

  • pushState = "Add a new fake URL"

  • replaceState = "Swap the current fake URL"

  • popstate = "Hey! User hit back/forward"


✅ Real Use Cases

Use CaseMethod
SPA page navigationpushState()
Modal route URL (/post/123)pushState()
Analytics tracking per viewpushState()
Handle browser back/forwardpopstate listener
Fix broken refresh URLsreplaceState()




8. Web Workers?

Ans. 

1. Formal Definition & Example

Web Workers allow you to run JavaScript in background threads, separate from the main UI thread. This lets you perform heavy computations without freezing the user interface.

✅ Basic Example: Creating a Worker

// main.js const worker = new Worker('worker.js'); worker.postMessage('Start calculation'); worker.onmessage = (event) => { console.log('Result from worker:', event.data); };


// worker.js self.onmessage = (event) => { const result = heavyComputation(event.data); self.postMessage(result); }; function heavyComputation(data) { // Some CPU-intensive task let sum = 0; for (let i = 0; i < 1e8; i++) sum += i; return sum; }

2. Code Explanation

  • new Worker('worker.js'): Spawns a new thread running worker.js.

  • postMessage(): Sends data to the worker.

  • onmessage: Listens for messages from the worker.

  • Inside worker, self.onmessage listens to main thread.

  • self.postMessage() sends data back.


3. Easy/Slang Explanation

Web Workers are like your multitasking buddies. While the main thread keeps the UI smooth, workers do the heavy lifting in the background — no freezing, no lag.


✅ Why Use Web Workers?

BenefitDetails
Non-blocking UI    Heavy tasks don't freeze the UI
Parallel processing    Run multiple scripts simultaneously
Responsive apps    Better UX with smooth animations & inputs

⚠️ Important Notes

  • Web Workers cannot access DOM directly.

  • Communication is done only via message passing.

  • Supported in all modern browsers.

  • Use for heavy calculations, data processing, or background fetch.





9. Service Workers?

Ans. 

1. Formal Definition & Example

Service Workers are special scripts that run in the background, separate from web pages, enabling features like offline caching, push notifications, and background sync. They act as a programmable network proxy, intercepting network requests and managing responses.

✅ Basic Example: Registering a Service Worker

if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then((reg) => { console.log('Service Worker registered:', reg); }) .catch((err) => { console.error('Service Worker registration failed:', err); }); }

2. How a Service Worker Script (sw.js) Looks

self.addEventListener('install', (event) => { console.log('Service Worker installed'); event.waitUntil( caches.open('v1').then((cache) => { return cache.addAll([ '/', '/index.html', '/styles.css', '/app.js' ]); }) ); }); self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request) .then((response) => { return response || fetch(event.request); }) ); });

3. Easy/Slang Explanation

Service Workers are your website’s offline bodyguards. They stand between your app and the network, catching requests and serving cached stuff when offline or slow. This makes your app work even with bad or no internet.


✅ What Service Workers Enable

FeatureDescription
Offline supportServe cached files without internet
Background syncSync data when the connection is back
Push notificationsReceive messages even if app isn’t open
Network proxyIntercept and customize network requests
Performance optimizationCache assets smartly to speed up loading


⚠️ Important Notes
  • Must be served over HTTPS (except localhost).

  • Runs in a separate thread from main JS.

  • Can’t access DOM directly.

  • Lifecycle events: install, activate, fetch, message.


































































































































Comments

Popular posts from this blog

ReactJs Notes

NextJS Notes

HTML NOTES