JavaScript Notes
🔰 Phase 1: JavaScript Fundamentals
Topics:
What is JavaScript? How JS runs in browser
Variables: let
, const
, var
(and hoisting)
Data Types (primitive vs non-primitive)
Type Conversion & Coercion
Operators: arithmetic, comparison, logical, ternary
Conditional statements: if
, else
, switch
Loops: for
, while
, do while
, for...in
, for...of
Functions:
Declaration vs Expression
Parameters vs Arguments
Arrow Functions
IIFE (Immediately Invoked Function Expression)
What is JavaScript? How JS runs in browser
Variables: let
, const
, var
(and hoisting)
Data Types (primitive vs non-primitive)
Type Conversion & Coercion
Operators: arithmetic, comparison, logical, ternary
Conditional statements: if
, else
, switch
Loops: for
, while
, do while
, for...in
, for...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.
Create a basic calculator
Write functions like factorial, prime check, palindrome, etc.
🔁 Phase 2: Intermediate JavaScript
Topics:
Arrays:
Methods: push
, pop
, shift
, unshift
, slice
, splice
map
, filter
, reduce
, find
, some
, every
Strings:
Methods: split
, substring
, includes
, indexOf
, replace
Objects:
Object creation, this
, Object.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.getElementById
, querySelector
, etc.
Event Listeners: click
, input
, keydown
, etc.
Browser Events & Forms
Arrays:
Methods:
push
,pop
,shift
,unshift
,slice
,splice
map
,filter
,reduce
,find
,some
,every
Strings:
Methods:
split
,substring
,includes
,indexOf
,replace
Objects:
Object creation,
this
,Object.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.getElementById
,querySelector
, etc.Event Listeners:
click
,input
,keydown
, etc.
Browser Events & Forms
Practice:
Todo list app
JS Clock/Stopwatch
Tip calculator
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
bind
, call
, apply
Promises & Async/Await
Event Loop, Microtasks vs Macrotasks
setTimeout, setInterval
Debounce & Throttle
Modules (import/export)
Error Handling (try/catch/finally)
JSON & Fetch API
Execution Context
Call Stack
Hoisting
Scope Chain
Closures
Debouncing of Function
this
keyword in depth
bind
, call
, apply
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
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
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
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
Local Storage
Session Storage
Cookies
Navigator API
Geolocation API
Clipboard API
History API
Web Workers
Service Workers
------------------------------------------------------------------
Phase 1: JavaScript Fundamentals
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.
🔍 What’s Happening In Code:
-
HTML renders
<h1>Hello</h1>
-
JS code runs inside
<script>
-
name
is defined as"Faraz"
-
The browser’s DOM API (
document.getElementById
) accesses the<h1>
element. -
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.
Variables in JS
A variable is a named container that holds a value. JavaScript provides three ways to declare variables:
Keyword | Scope | Reassignment | Redeclaration | Hoisted |
---|---|---|---|---|
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 asundefined
-
let
andconst
are hoisted but not initialized, they stay in Temporal Dead Zone (TDZ) until their declaration line
What’s Happening In code?
-
var a
is hoisted and initialized asundefined
, soconsole.log(a)
doesn’t crash. -
let b
andconst c
are hoisted, but not initialized. So trying to access them before their declaration throws aReferenceError
. -
After the declaration line, all three hold their expected values.
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.
🔹 ES5 Style
🔹 ES6+ Style
🔍 What's New in ES6:
-
const
replacesvar
-
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?
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
🔍 Explanation of Code:
-
x
andy
are primitives – wheny = x
, it copies the value ofx
. So changingy
doesn’t affectx
. -
person1
andperson2
are non-primitives (objects) – assigningperson2 = person1
copies the reference, not the actual object. So modifyingperson2.name
also changesperson1.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:
✅ 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:
Code Example + Explanation
🔍 Explanation of Code:
-
Number(str)
is a manual conversion from string to number. -
In
"5" + 1
, JS converts1
to string and concatenates →"51"
. -
In
"5" - 1
, JS converts"5"
to number →4
. -
In
true + 1
,true
becomes1
→ result is2
.
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?
Operators in JavaScript
Operators are symbols or keywords that let you perform operations on values or variables.
Arithmetic Operators
Used for mathematical operations:
Operator | Meaning | 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
):
Operator | Meaning | Example |
---|---|---|
== | 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 |
---|---|---|
&& | AND | a && b |
` | Backtecks | `Faraz` |
! | NOT | !a |
Ternary Operator
A shorthand for if...else
Example:
Code Example + Explanation
🔍 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.”
7. Conditional statements: if, else, switch?
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...else
Statement
Provides an alternative block if the condition is false
.
else if
Checks multiple conditions in sequence.
switch
Statement
Best for checking a value against multiple fixed options (cases).
Code Example + Explanation
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 matchescase "Saturday"
and prints"Weekend vibes"
-
break
is used to stop checking further once a match is found inswitch
.
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?
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)
Code Example + Explanation
Explanation of Code:
-
function greet(name)
→ declares a function that takes one input calledname
-
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:
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:
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?
✅ 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):
Code Example + Explanation
🔍 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 variablespeak
exists due toconst
, 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?
✅ 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):
Code Example + Explanation
🔍 Explanation:
-
a
andb
are the parameters defined in the function header. -
5
and3
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:
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?
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).Code Example + Explanation
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:
-
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.
Slang / Easy Mode
Arrow functions are like the lazy guy’s way of writing functions.
Instead of:
You just go:
-
They’re short.
-
They look clean.
-
But be careful — they don't have their own
this
, so don’t use them when you needthis
(like in class methods or certain object contexts).
12. IIFE (Immediately Invoked Function Expression)?
Formal Example:
Code Example + Explanation
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:
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?
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:
Here:
-
"apple"
is at index 0 -
"banana"
is at index 1 -
"cherry"
is at index 2
Code Example + Explanation:
🔍 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?
Formal Definitions with Examples
Method | Definition |
---|---|
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
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?
Formal Definitions with Examples
Method | Purpose |
---|---|
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
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?
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:
🧪 2. Code Example with Explanation
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?
Formal Definition with Example
JavaScript provides built-in string methods that help manipulate or retrieve parts of a string:
Method | Description |
---|---|
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 |
🧪 2. Code Example with Explanation
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:
6. Objects?
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:
Here:
-
"name"
,"age"
,"isStudent"
are keys (also called properties) -
"Faraz"
,22
,true
are their corresponding values
🧪 2. Code Example with Explanation
💡 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:
-
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 ?
🔧 1. Object Creation
🧠 Formal Definition:
There are multiple ways to create objects in JavaScript:
-
Object literals
-
new Object()
constructor -
Object.create()
📦 Example:
🧪 Code + Explanation:
-
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:
🧪 Code + Explanation:
-
Inside
sayHi()
,this
refers touser
-
Outside an object,
this
might point towindow
(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:
🧪 Code + Explanation:
-
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?
1. Destructuring
🔹Formal Definition:
Destructuring is a JavaScript expression that allows unpacking values from arrays or properties from objects into distinct variables.
Example:
Code Example:
Explanation:
-
[a, b, c] = arr
: takes values from the arrayarr
and assigns them to variablesa
,b
,c
. -
{ username, email } = user
: pulls outusername
andemail
from theuser
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:
Code Example:
Explanation:
-
...obj1
spreads the properties ofobj1
intoobj2
. -
...nums
copies all elements ofnums
intocopy
.
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:
Code Example:
Explanation:
-
In array destructuring: grabs
first
, then dumps the rest inrest
. -
In object destructuring: pulls out
a
, and collects remaining keys inothers
.
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:
Code Example:
Explanation:
-
If any part before
?.
is null/undefined, it short-circuits and returnsundefined
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?
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:
2. Code Example with Explanation
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:
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:
You can do:
Much cleaner. It’s like string building on steroids.
10. ES6+ Features: let/const, arrow functions, default parameters?
✅ 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:
b. Arrow Functions
Arrow functions are a shorter way to write functions using =>
. They do not bind their own this
(lexical this
).
Example:
c. Default Parameters
Allows setting default values for function parameters if no value (or undefined
) is passed.
Example:
✅ 2. Code Examples with Explanation
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?
✅ 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:
✅ 2. Code Example with Explanation
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?
✅ 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 inif
,for
, etc.) withlet
andconst
.
Closure
A closure is a function that remembers the variables from its outer scope, even after the outer function has finished executing.
Example:
✅ 2. Code Example with Explanation
Explanation:
-
createCounter
creates a privatenum
. -
The returned function “remembers”
num
even aftercreateCounter
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?
✅ 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:
✅ 2. Code Example with Explanation
Explanation:
-
calculate
is the higher-order function. -
It accepts a function (
operation
) as an argument and invokes it. -
add
andmultiply
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?
✅ 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:
✅ 2. Code Example with Explanation
What’s happening:
-
getElementById()
grabs elements by ID. -
addEventListener()
listens for events (likeclick
). -
.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:
Task | Method |
---|---|
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.?
✅ 1. Formal Definition with Example
These are DOM selection methods used to fetch HTML elements from the document for manipulation.
Method | Description | Returns |
---|---|---|
getElementById(id) | Selects an element by ID | Single Element |
getElementsByClassName(class) | Selects all elements with that class | HTMLCollection (live) |
getElementsByTagName(tag) | Selects all elements with that tag | HTMLCollection (live) |
querySelector(selector) | Returns first element matching any valid CSS selector | Single Element |
querySelectorAll(selector) | Returns all elements matching a CSS selector | Static NodeList |
✅ 2. Code Example with Explanation
-
querySelectorAll
returns a static list → supportsforEach
-
getElementsByClassName
returns a live collection → needsArray.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:
Selector | Use Case | Returns |
---|---|---|
getElementById("id") | Fastest for unique IDs | Element |
getElementsByClassName("class") | Multiple elements | Live HTMLCollection |
getElementsByTagName("tag") | All matching tags | Live HTMLCollection |
querySelector("css") | First match via CSS | Element |
querySelectorAll("css") | All matches via CSS | Static NodeList |
16. Event Listeners: click, input, keydown, etc.?
✅ 1. Formal Definition with Example
Event Listeners in JavaScript let you respond to user interactions (clicks, typing, hovering, etc.).
They are added using:
Common Event Types:
Event | Triggered When... |
---|---|
click | User clicks an element |
input | User types or modifies input |
keydown | Any key is pressed down |
keyup | Key is released |
mouseover | Mouse hovers over element |
submit | A form is submitted |
✅ 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
You must use the same function reference to remove it.
17. Browser Events & Forms?
✅ 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:
Event | What it does |
---|---|
load | Fires when page fully loads |
DOMContentLoaded | Fires when DOM is ready (before images/CSS) |
resize | Window size changes |
submit | A form is submitted |
change | Input value changes (on blur) |
input | Runs as user types (real-time input) |
🧠 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
--------------------------------------------------------------------------
🧠 Phase 3: Advanced JavaScript
1. Execution Context?
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:
-
First, the Global Execution Context is created.
-
When
greet()
is called, a Function Execution Context is created for it.
2. Code Example + Explanation:
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 insidefoo
's local context. -
The function has access to both
x
(from global scope) andy
(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?
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:
Call Stack Flow:
-
Global()
pushed -
welcome()
pushed -
greet()
pushed -
greet()
popped -
welcome()
popped -
Global()
popped
2. Code Example + Explanation:
Call Stack Execution:
-
Global Execution Context
→ pushed -
a()
called →a Execution Context
→ pushed -
b()
called →b Execution Context
→ pushed -
c()
called →c Execution Context
→ pushed -
c()
finishes → popped -
b()
finishes → popped -
a()
finishes → popped -
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:
3. Stack Overflow?
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:
2. Code Example + Explanation:
Explanation:
-
countDown
calls itself withn - 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:
✅ Always have a base case in recursion or rewrite with loops if stack usage is too high.
4. Tail Call Optimization (TCO)?
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):
2. Code Example + Explanation:
Without TCO:
Each call needs to remember n
to do the addition after recursion returns → stack builds up → 💥 stack overflow.
With TCO:
-
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 Optimization – no 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?
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:
Output:
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:
Output:
Stack/Queue Flow:
-
Global()
→ pushed -
one()
called → pushed -
console.log("One")
-
two()
called → pushed -
console.log("Two")
-
two()
finishes → popped -
Hits
await
→ pausesone()
here -
one()
is popped -
console.log("Global End")
-
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?
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:
Internally behaves like:
2. Code Examples + Explanation:
🧠 Hoisting with var
:
-
var x
is hoisted → initialized withundefined
. -
The assignment
x = 10
happens later.
❌ Hoisting with let
/ const
:
-
let
andconst
are also hoisted, but stay in a Temporal Dead Zone (TDZ) until their line is reached → can't access them before declaration.
✅ Function Hoisting:
-
Function declarations are fully hoisted – name + body – so you can call them before they appear in code.
⚠️ Function Expression Hoisting:
-
sayHi
is hoisted asundefined
(because it's avar
), so calling it before assignment causesTypeError: 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 dumbundefined
until it's set. -
let
andconst
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 Type | Hoisted? | 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?
1. Formal Definition + Example:
The Scope Chain is the mechanism JavaScript uses to resolve variable names. When a variable is referenced, JS looks:
-
In the current/local scope.
-
If not found, it goes up one level to the outer (parent) scope.
-
Keeps going until it reaches the global scope.
-
If still not found → ❌
ReferenceError
.
This “chain” of scopes is created lexically — based on where code is written, not called.
Example:
The scope chain here:
inner → outer → global
.
2. Code Example + Explanation:
🧠 Scope Chain Lookup:
-
JS looks for
x
inchild()
→ not found. -
Moves to
parent()
→ not found. -
Moves to global → ✅ found.
-
Same for
y
,z
.
❌ Variable Not in Scope Chain:
-
test()
is defined beforeuser
exists in any outer scope → it can’t seeuser
, 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 Type | Can Access |
---|---|
Function Scope | Its own + parent + global |
Global Scope | Only its own stuff |
No Scope | ReferenceError |
8. Closures?
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:
✅ count
is remembered by inner()
even after outer()
is done running.
2. Code Example + Breakdown:
🔁 Simple Closure Counter:
What’s Happening:
-
value
lives increateCounter()
’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?
✅ 1. Formal Definition with Example
Debouncing is a programming technique that ensures a function is only executed after a certain delay — and only once — after 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
🔍 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?
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:
2. Different this
Scenarios with Code + Explanation
🧠 Global Context (non-strict mode)
-
In the global scope,
this
refers to the global object. -
In the browser:
window
-
In Node.js:
global
🔒 Strict Mode
-
In strict mode,
this
inside functions is undefined (not global).
👤 Object Method
⚠️ Losing Context (Detached method)
-
this
gets lost because the method is called without context.
➕ this
in Arrow Functions
✅ Arrow functions don’t have their own this
— they inherit it from their lexical scope.
👨🔧 Constructor Function
-
this
refers to the newly created object.
🧠 Using call
, apply
, bind
-
call()
andapply()
setthis
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
Situation | this 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?
1. Formal Definition + Example:
All three methods (bind
, call
, apply
) are used to manipulate the value of this
in a function.
Method | What 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:
✅ call() – Immediate Execution, args separated
-
First arg is
this
, rest are normal function arguments.
✅ apply() – Immediate Execution, args as array
-
Same as
call()
but arguments passed as an array.
✅ bind() – Returns a new function, doesn't run immediately
-
bind()
returns a new function wherethis
is locked toperson
.
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
Method | When to Use | Executes Immediately? | Args Format |
---|---|---|---|
call() | Run a function with specific this | ✅ Yes | Comma-separated |
apply() | Like call but with arrays | ✅ Yes | Array |
bind() | Create a new function with this | ❌ No | Comma-separated |
Real Use Case Example (Event Listener Fix):
12. Promises & Async/Await?
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:
-
Promise starts in pending state.
-
After 1 second, it resolves with
"Success!"
. -
.then()
handles success;.catch()
handles errors.
🧪 Async/Await Syntax:
-
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
Concept | Description | Syntax 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 insideasync
functions.
13. Event Loop, Microtasks vs Macrotasks?
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:
Feature | Microtasks | Macrotasks |
---|---|---|
Examples | Promise.then() , MutationObserver | setTimeout() , setInterval() , I/O |
Priority | Higher priority — executed before rendering and macrotasks | Lower priority — executed after microtasks and rendering |
When they run | After the current stack is empty, but before the browser repaints | After microtasks and rendering, picked from the task queue |
Runs repeatedly | Runs until microtask queue is empty | One macrotask per event loop tick |
3. Event Loop Flow (Simplified):
-
Run all synchronous code (call stack empties).
-
Run all microtasks (e.g., promise callbacks).
-
Render UI (if needed).
-
Run one macrotask (e.g.,
setTimeout
callback). -
Repeat.
4. Code Example + Explanation:
Output:
-
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 Type | Priority | Examples | When executed |
---|---|---|---|
Microtasks | High | Promises, MutationObserver | Right after current execution stack empties, before rendering |
Macrotasks | Low | setTimeout, I/O, UI events | After microtasks and rendering |
14. setTimeout and setInterval?
1. Formal Definition + Example:
-
setTimeout(fn, delay)
: Schedules a functionfn
to run once after at leastdelay
milliseconds. -
setInterval(fn, delay)
: Schedules a functionfn
to run repeatedly everydelay
milliseconds until cleared.
2. Code Examples + Explanation:
setTimeout
– Run Once After Delay
Output:
-
The callback runs after synchronous code finishes and after approx 2 seconds.
setInterval
– Run Repeatedly
-
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
andclearInterval
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 | Once | After delay + event loop wait | clearTimeout(id) |
setInterval | Repeatedly | Every delay + event loop wait | clearInterval(id) |
15. Debounce & Throttle?
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)
-
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)
-
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
Technique | When to Use | How it Works |
---|---|---|
Debounce | After event stops firing | Delays call until event quiet for delay |
Throttle | Limit how often during event | Calls immediately, then blocks calls till limit time passed |
16. JavaScript Modules (import/export)?
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
app.js
-
You export multiple named things.
-
Import with curly braces matching the names.
✅ Default Export & Import
logger.js
app.js
-
Default export means you import without
{}
and can rename as you want.
✅ Renaming Imports/Exports
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
Feature | Syntax | Notes |
---|---|---|
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
)?
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 insidetry
. -
finally
: Always runs aftertry
andcatch
(whether error occurred or not).
2. Code Examples + Explanation:
-
If
riskyFunction()
throws, code jumps tocatch
. -
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
Block | Purpose |
---|---|
try | Code that might fail |
catch | Handle error if try fails |
finally | Run code always, cleanup or final steps |
Bonus: Throwing Your Own Errors
18. JSON & Fetch API?
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:
-
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()
returns a Promise with the response. -
Call
.json()
to parse JSON body (also returns Promise).
4. Fetch API Example (POST request):
-
Use
method
to specify HTTP method. -
Use
headers
to specify content type. -
Use
body
withJSON.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
Concept | What it does | Example 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?
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.
2. What Happens Internally with new
:
When you do new Person("Faraz", 22)
:
-
A new empty object is created:
{}
-
this
is set to that object inside the function -
Properties/methods are added to
this
-
The object is returned automatically
3. Prototype Optimization (Good Practice):
Instead of defining functions inside the constructor (wasteful), put them on the prototype:
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 withoutnew
,this
becomesundefined
or global object (bad).
2. Prototypes & Prototype Chain in JavaScript?
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:
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
.
3. Function Prototypes
Every function in JS has a prototype
property which is used when that function is used as a constructor.
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 functions | Property on objects |
Used to build __proto__ | Points to the function's prototype |
Used during construction | Used during lookup |
6. Visual
3. ES6 Classes?
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:
Under the hood,
Person
is still a function, andgreet()
lives onPerson.prototype
.
2. Class Inheritance
3. Easy/Slang Explanation
Classes in JS are just nicer wrappers over how prototypes work.
Instead of sayingfunction Dog() {}
, you now sayclass Dog {}
— same game, new skin.
4. Key Features
Feature | Description |
---|---|
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
6. Behind the Scenes
So even class
is just a function constructor, but in a cleaner way.
4. Inheritance in JS?
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):
2. Modern ES6+ Class Inheritance
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 writeextends
and usesuper()
like in other languages.
4. Under the Hood – Prototype Chain
-
Dog.prototype
links toAnimal.prototype
-
max.__proto__
→Dog.prototype
-
Dog.prototype.__proto__
→Animal.prototype
That's the chain.
5. Key Concepts
Concept | Meaning |
---|---|
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?
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)
📌 Explanation:
-
#balance
is encapsulated: cannot be accessed directly. -
Methods like
deposit
,withdraw
, andgetBalance
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
✅ This is closure-based encapsulation & abstraction in functional style.
6. Factory Functions vs Constructor?
🔹 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
👷♂️ Constructor Function
🔹 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 withthis
.
🔹 4. Pros/Cons Table
Feature | Factory Function | Constructor 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)
7. Composition over Inheritance?
🔹 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)
✅ Composition Example (Loose coupling)
🔹 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 & reusable | Rigid & tightly coupled |
Easy to test and isolate behaviors | Harder to test deep hierarchies |
Encourages separation of concerns | Inheritance 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
7. Pure Functions and Immutability?
🔹 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:
🚫 Impure Function (side effect):
✅ Immutability
Immutability means data cannot be changed once created. Instead, you create and work with copies of data.
Example:
🔹 2. Code Example + Explanation
✅ Pure + Immutable Example:
🔹 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
Concept | Why it’s 🔥 Useful |
---|---|
Pure Functions | Easy to test, debug, and reuse |
Immutability | Prevents accidental bugs, makes code safer |
🔹 5. Real-World Usage (React-friendly)
React promotes both:
✅ Pure
✅ Immutable
✅ Predictable behavior
8. Currying vs Partial Application in JavaScript?
🔹 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:
With arrow functions:
✅ Partial Application
Partial application is when you fix some arguments of a function, creating a new function with fewer parameters.
Example:
Or with .bind()
:
🔹 2. Key Differences
Feature | Currying | Partial Application |
---|---|---|
Transformation | Converts to unary functions | Fixes some arguments |
Return type | Series of single-arg functions | New function with fewer args |
Focus | All args separated | Pre-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:
Partial Application for logging:
🌐 Phase 5: Browser APIs & Environment
1. Local Storage?
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:
2. Code Example with Explanation
-
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:
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?
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:
2. Code Example with Explanation
🧠 Like localStorage, it only stores strings — use JSON.stringify()
/ JSON.parse()
for objects:
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:
Feature | localStorage | sessionStorage |
---|---|---|
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?
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:
2. Code Example with Explanation
-
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
Feature | Cookies | localStorage | sessionStorage |
---|---|---|---|
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?
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:
2. Code Examples with Explanation
✅ Basic Info
✅ Check if Online
✅ Geolocation (with permission)
✅ Clipboard API
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
Feature | Code 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?
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:
2. Code Example with Explanation
✅ Basic Usage
✅ Options (Accuracy, Timeout, Max Age)
✅ Watch Position (Track Movement)
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?
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:
2. Code Examples with Explanation
✅ Copy to Clipboard
✅ Paste from Clipboard
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 Case | Code |
---|---|
Copy coupon code | clipboard.writeText(code) |
Paste note content | clipboard.readText() |
Share links easily | clipboard.writeText(window.location) |
Copy code blocks | Button triggers clipboard.writeText() |
7. History API?
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:
2. Code Examples with Explanation
✅ Push a New State (Change URL without Reload)
-
Adds a new entry to the browser history stack.
-
Doesn’t reload the page — just changes the URL.
✅ Replace Current State
-
Replaces the current entry instead of adding a new one.
✅ Listen for Navigation (Back/Forward)
✅ Navigate Manually
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 Case | Method |
---|---|
SPA page navigation | pushState() |
Modal route URL (/post/123 ) | pushState() |
Analytics tracking per view | pushState() |
Handle browser back/forward | popstate listener |
Fix broken refresh URLs | replaceState() |
8. Web Workers?
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
2. Code Explanation
-
new Worker('worker.js')
: Spawns a new thread runningworker.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?
Benefit | Details |
---|---|
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?
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
2. How a Service Worker Script (sw.js) Looks
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
Feature | Description |
---|---|
Offline support | Serve cached files without internet |
Background sync | Sync data when the connection is back |
Push notifications | Receive messages even if app isn’t open |
Network proxy | Intercept and customize network requests |
Performance optimization | Cache assets smartly to speed up loading |
-
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
Post a Comment