JavaScript Notes
JavaScript Notes
presents
JavaScript
Complete Notes
Beginner to Advanced | With Definitions & Simple Examples
What is JavaScript?
JavaScript was created by Brendan Eich in 1995. It was originally built for web browsers, but today it
runs almost everywhere — servers, mobile apps, and even robots.
● It is the language of the Web — every browser understands it.
● It can read and change HTML, react to clicks, send data to servers, and much more.
● It is the only language that runs natively inside the browser.
● On the server side, it runs using [Link].
TIP You do not need to memorise all versions. Focus on ES5 and ES6 — they are the most important.
02. Variables & Declarations
Definition: Variable — A named container that stores a value. Think of it like a labelled box where you
can put a value and refer to it by the label name.
What is Scope?
Definition: Scope — The area of code where a variable can be accessed. Think of it like different
rooms in a house — a variable inside a room cannot be seen from outside.
⯈ Block Scope Example
1 // let and const are block-scoped (inside {} curly braces)
2 if (true) {
3 let message = "I am inside the block";
4 [Link](message); // Works fine
5 }
6
7 // [Link](message); // ERROR! message is not visible here
What is Hoisting?
Definition: Hoisting — JavaScript moves variable and function declarations to the top of their scope
before the code runs. This is called hoisting.
⯈ Hoisting with var
1 [Link](name); // undefined (no error)
2 var name = 'Alice'; // var is hoisted to top
3
4 // JavaScript actually sees it as:
5 // var name;
6 // [Link](name); // undefined
7 // name = 'Alice';
⯈ Hoisting with let — Temporal Dead Zone
1 // [Link](score); // ReferenceError — cannot access before init
2 let score = 100;
WARNING Always declare variables at the top of your code to avoid hoisting confusion.
Naming Conventions
● camelCase — for variables and functions: firstName, totalScore
● UPPER_SNAKE_CASE — for constants: MAX_LIMIT, API_KEY
● PascalCase — for classes: UserProfile, ShoppingCart
Destructuring Assignment
Definition: Destructuring — A shortcut to unpack values from arrays or objects into separate
variables in one line.
⯈ Array Destructuring
1 // Old way:
2 const arr = [10, 20, 30];
3 const a = arr[0]; // 10
4 const b = arr[1]; // 20
5
6 // New way with destructuring:
7 const [x, y, z] = [10, 20, 30];
8 [Link](x); // 10
9 [Link](y); // 20
Output: 10 20
⯈ Object Destructuring
1 const person = { name: "Alice", age: 25 };
2
3 // Extract properties into variables
4 const { name, age } = person;
5 [Link](name); // Alice
6 [Link](age); // 25
Output: Alice 25
03. Data Types
Definition: Data Type — The kind/category of value a variable holds. JavaScript has 8 built-in data
types, split into Primitive (simple) and Non-primitive (complex) types.
1. Number
Definition: Number — Used for all numeric values — integers, decimals, negative numbers, Infinity,
and NaN.
⯈ Example
1 let age = 25; // whole number
2 let price = 9.99; // decimal
3 let negative = -100; // negative
4 let big = 1_000_000; // underscore for readability
5 let infinity = Infinity;
6 let notNumber = NaN; // result of invalid math
7
8 [Link](10 / 0); // Infinity
9 [Link]("abc" * 2); // NaN
2. String
Definition: String — A sequence of characters (text) enclosed in single quotes, double quotes, or
backticks.
⯈ Example
1 let name = "Alice"; // double quotes
2 let city = 'Mumbai'; // single quotes
3 let country = `India`; // backticks (template literal)
4
5 // Joining strings (concatenation)
6 let greeting = "Hello " + name; // "Hello Alice"
7 [Link](greeting);
8
9 // Template literal — embed variables using ${}
10 let intro = `My name is ${name} from ${city}.`;
11 [Link](intro);
Output: Hello Alice | My name is Alice from Mumbai.
3. Boolean
Definition: Boolean — Represents only two values: true or false. Used in conditions and comparisons.
⯈ Example
1 let isLoggedIn = true;
2 let hasError = false;
3
4 // Result of comparisons is always boolean
5 [Link](10 > 5); // true
6 [Link](10 === 5); // false
7
8 let age = 18;
9 [Link](age >= 18); // true
4. Undefined
Definition: Undefined — A variable that has been declared but NOT yet given a value has the value
undefined.
⯈ Example
1 let score;
2 [Link](score); // undefined
3
4 // A function that returns nothing gives undefined
5 function doNothing() {}
6 [Link](doNothing()); // undefined
5. Null
Definition: Null — Represents the intentional absence of any value. You manually set a variable to null
to say 'this has no value right now'.
⯈ Example
1 let user = null; // no user logged in
2 [Link](user); // null
3
4 // Later when user logs in:
5 user = { name: "Alice" };
6 [Link](user); // { name: 'Alice' }
TIP null means 'empty on purpose'. undefined means 'not yet set'. They are different!
6. Symbol (ES6)
Definition: Symbol — A unique and immutable value, mainly used as unique object property keys. No
two symbols are ever equal.
⯈ Example
1 const id1 = Symbol("id");
2 const id2 = Symbol("id");
3 [Link](id1 === id2); // false — always unique
7. BigInt (ES2020)
Definition: BigInt — Used for very large integers that exceed the safe integer limit of regular numbers.
⯈ Example
1 const big = 9007199254740991n; // note the 'n' at the end
2 [Link](big + 1n); // 9007199254740992n
Non-Primitive: Object
Definition: Object — A collection of key-value pairs. Arrays, functions, and dates are all objects.
Unlike primitives, objects are stored as references.
⯈ Example
1 // Object — key: value pairs
2 const person = { name: "Bob", age: 30 };
3
4 // Array — ordered list (also an object)
5 const colors = ['red', 'green', 'blue'];
6
7 // Function — also an object in JS
8 function greet() { return 'Hello!'; }
Type Conversion
Definition: Type Conversion — Converting a value from one data type to another. Can be automatic
(implicit) or manual (explicit).
⯈ Explicit Conversion
1 // To Number
2 Number("42") // 42
3 Number(true) // 1
4 Number(false) // 0
5 Number("hello") // NaN
6
7 // To String
8 String(42) // "42"
9 String(true) // "true"
10
11 // To Boolean
12 Boolean(0) // false ← 0 is falsy
13 Boolean("") // false ← empty string is falsy
14 Boolean(null) // false
15 Boolean(1) // true
16 Boolean("hello") // true
04. Operators
Definition: Operator — A special symbol or keyword that performs an operation on one or more
values (called operands). Example: + adds two numbers.
1. Arithmetic Operators
Used to perform mathematical calculations.
⯈ Example
1 let a = 10, b = 3;
2
3 [Link](a + b); // 13 — Addition
4 [Link](a - b); // 7 — Subtraction
5 [Link](a * b); // 30 — Multiplication
6 [Link](a / b); // 3.33.. — Division
7 [Link](a % b); // 1 — Remainder (Modulo)
8 [Link](a ** b); // 1000 — Exponentiation (10 to power 3)
9
10 // Increment and Decrement
11 let x = 5;
12 x++; // x becomes 6 (add 1)
13 x--; // x becomes 5 (subtract 1)
14 [Link](x); // 5
2. Assignment Operators
Definition: Assignment Operator — Assigns a value to a variable. The basic one is = but there are
shortcuts for common operations.
⯈ Example
1 let x = 10; // basic assignment
2
3 x += 5; // same as x = x + 5 → x is now 15
4 x -= 3; // same as x = x - 3 → x is now 12
5 x *= 2; // same as x = x * 2 → x is now 24
6 x /= 4; // same as x = x / 4 → x is now 6
7 x %= 4; // same as x = x % 4 → x is now 2
8 x **= 3; // same as x = x ** 3 → x is now 8
3. Comparison Operators
Definition: Comparison Operator — Compares two values and returns true or false (a Boolean
result).
⯈ == vs ===
1 // == loose equality — converts types before comparing
2 [Link](5 == "5"); // true (number vs string, converted)
3 [Link](0 == false); // true
4
5 // === strict equality — NO type conversion (recommended)
6 [Link](5 === "5"); // false (different types)
7 [Link](5 === 5); // true
8
9 // Other comparison operators
10 [Link](10 > 5); // true
11 [Link](10 >= 10); // true
12 [Link](3 < 5); // true
13 [Link](3 <= 2); // false
14 [Link](5 !== "5"); // true (strict NOT equal)
WARNING Always use === instead of ==. Using == can lead to unexpected bugs due to automatic type
conversion.
4. Logical Operators
Definition: Logical Operator — Combines multiple conditions. Returns true or false based on the
logic.
⯈ Example
1 // && (AND) — true ONLY if BOTH sides are true
2 [Link](true && true); // true
3 [Link](true && false); // false
4 [Link](5 > 3 && 10 > 7);// true
5
6 // || (OR) — true if AT LEAST ONE side is true
7 [Link](false || true); // true
8 [Link](false || false); // false
9
10 // ! (NOT) — flips true to false, false to true
11 [Link](!true); // false
12 [Link](!false); // true
13 [Link](!0); // true (0 is falsy, so !0 is true)
5. Ternary Operator
Definition: Ternary Operator — A one-line shortcut for if/else. Syntax: condition ? valueIfTrue :
valueIfFalse
⯈ Example
1 let age = 20;
2
3 // Long way:
4 // if (age >= 18) { status = 'Adult' } else { status = 'Minor' }
5
6 // Short way using ternary:
7 const status = age >= 18 ? "Adult" : "Minor";
8 [Link](status); // "Adult"
9
10 // Another example:
11 let marks = 75;
12 let result = marks >= 50 ? "Pass" : "Fail";
13 [Link](result); // Pass
1. if Statement
Definition: if — Runs a block of code only if the condition is true.
⯈ Simple if
1 let temperature = 32;
2
3 if (temperature > 30) {
4 [Link]("It is hot outside!");
5 }
Output: It is hot outside!
2. if...else Statement
Definition: if...else — If the condition is true, run first block. Otherwise, run the else block.
⯈ Example
1 let age = 15;
2
3 if (age >= 18) {
4 [Link]("You can vote.");
5 } else {
6 [Link]("You are too young to vote.");
7 }
Output: You are too young to vote.
4. switch Statement
Definition: switch — Checks one value against many possible cases. Cleaner than multiple if/else
when comparing the same variable.
⯈ Day Name
1 let day = 3;
2
3 switch (day) {
4 case 1:
5 [Link]("Monday");
6 break;
7 case 2:
8 [Link]("Tuesday");
9 break;
10 case 3:
11 [Link]("Wednesday");
12 break;
13 case 4:
14 [Link]("Thursday");
15 break;
16 case 5:
17 [Link]("Friday");
18 break;
19 default:
20 [Link]("Weekend!");
21 }
Output: Wednesday
WARNING Always write `break` at the end of each case, or execution will 'fall through' to the next case.
1. for Loop
Definition: for Loop — The most common loop. Used when you know exactly how many times you
want to repeat something. Has 3 parts: start, condition, and update.
⯈ Count from 1 to 5
1 // for (start; condition; update)
2 for (let i = 1; i <= 5; i++) {
3 [Link](i);
4 }
5 // Output: 1 2 3 4 5
⯈ Loop through an Array
1 const fruits = ['apple', 'banana', 'mango'];
2
3 for (let i = 0; i < [Link]; i++) {
4 [Link](fruits[i]);
5 }
6 // Output: apple banana mango
2. while Loop
Definition: while Loop — Keeps repeating as long as the condition is true. Use it when you do not
know in advance how many times to loop.
⯈ Example
1 let count = 1;
2
3 while (count <= 5) {
4 [Link]('Count:', count);
5 count++; // IMPORTANT: update the variable or loop runs forever!
6 }
7 // Output: Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
WARNING Always update the loop variable inside a while loop. Forgetting to do so creates an infinite loop
that crashes your browser.
3. do...while Loop
Definition: do...while Loop — Similar to while, but it always runs the code block AT LEAST ONCE,
even if the condition is false from the start.
⯈ Example
1 let num = 10;
2
3 do {
4 [Link]('Ran once with num =', num);
5 num++;
6 } while (num < 5); // condition is false, but code ran once
7
8 // Output: Ran once with num = 10
4. for...of Loop (ES6)
Definition: for...of — The easiest way to loop through arrays, strings, or any iterable. Directly gives
you the VALUE at each step.
⯈ Loop through Array
1 const colors = ['red', 'green', 'blue'];
2
3 for (const color of colors) {
4 [Link](color);
5 }
6 // Output: red green blue
⯈ Loop through String
1 for (const char of "Hello") {
2 [Link](char);
3 }
4 // Output: H e l l o
5. for...in Loop
Definition: for...in — Loops through the KEYS (property names) of an object.
⯈ Example
1 const student = { name: 'Raj', age: 20, city: 'Delhi' };
2
3 for (const key in student) {
4 [Link](key + ': ' + student[key]);
5 }
6 // Output:
7 // name: Raj
8 // age: 20
9 // city: Delhi
1. Function Declaration
Definition: Function Declaration — The classic way to define a function using the `function` keyword.
It is hoisted, so it can be called even before it is defined.
⯈ Example
1 // Define the function
2 function greet(name) {
3 return "Hello, " + name + "!";
4 }
5
6 // Call the function
7 [Link](greet("Alice")); // Hello, Alice!
8 [Link](greet("Bob")); // Hello, Bob!
Output: Hello, Alice! | Hello, Bob!
2. Function Expression
Definition: Function Expression — A function stored in a variable. It is NOT hoisted, so it must be
defined before calling it.
⯈ Example
1 const square = function(n) {
2 return n * n;
3 };
4
5 [Link](square(4)); // 16
6 [Link](square(7)); // 49
5. Default Parameters
Definition: Default Parameter — A value used when no argument is provided for that parameter.
⯈ Example
1 function greet(name = "Guest") {
2 return "Hello, " + name;
3 }
4
5 [Link](greet()); // Hello, Guest
6 [Link](greet("Alice")); // Hello, Alice
6. Return Statement
Definition: return — Sends a value back from the function to where it was called. A function stops
running when it hits return.
⯈ Example
1 function isAdult(age) {
2 if (age >= 18) {
3 return true; // stops here if age >= 18
4 }
5 return false; // only reaches here if age < 18
6 }
7
8 [Link](isAdult(20)); // true
9 [Link](isAdult(15)); // false
7. Closures
Definition: Closure — A function that remembers the variables from its outer scope even after the
outer function has finished running.
⯈ Simple Counter using Closure
1 function makeCounter() {
2 let count = 0; // this variable is 'remembered'
3
4 return function() {
5 count++;
6 return count;
7 };
8 }
9
10 const counter = makeCounter();
11 [Link](counter()); // 1
12 [Link](counter()); // 2
13 [Link](counter()); // 3
TIP Closures are used to create private variables and factory functions. This is a very important concept in
JavaScript!
8. Higher-Order Functions
Definition: Higher-Order Function — A function that takes another function as an argument OR
returns a function. This is possible because functions are first-class citizens in JS.
⯈ Example
1 // Takes a function as argument
2 function doTwice(fn, value) {
3 return fn(fn(value));
4 }
5
6 const double = x => x * 2;
7 [Link](doTwice(double, 3)); // 12 (3*2=6, 6*2=12)
08. Arrays
Definition: Array — An ordered list of values stored in a single variable. Each value has a position
number called an index, starting from 0.
1. Creating Arrays
⯈ Example
1 // Array literal — most common way
2 const fruits = ['apple', 'banana', 'mango'];
3 const numbers = [10, 20, 30, 40, 50];
4 const mixed = ['Alice', 25, true, null]; // can mix types
5
6 // Access by index (starts at 0)
7 [Link](fruits[0]); // apple
8 [Link](fruits[1]); // banana
9 [Link](fruits[2]); // mango
10
11 // Length of array
12 [Link]([Link]); // 3
1. Creating an Object
⯈ Example
1 // Object literal — most common
2 const person = {
3 name: 'Alice', // key: value
4 age: 25,
5 city: 'Mumbai',
6 isStudent: true,
7 };
8
9 // Access properties
10 [Link]([Link]); // Alice (dot notation)
11 [Link](person['age']); // 25 (bracket notation)
3. Methods in Objects
Definition: Method — A function stored as a property of an object. It describes what the object can
DO.
⯈ Example
1 const calculator = {
2 // Properties
3 brand: 'Casio',
4
5 // Methods
6 add: function(a, b) {
7 return a + b;
8 },
9 subtract(a, b) { // shorthand method
10 return a - b;
11 }
12 };
13
14 [Link]([Link](5, 3)); // 8
15 [Link]([Link](10, 4)); // 6
4. this Keyword
Definition: this — Inside a method, `this` refers to the object that owns the method. It lets you access
the object's own properties from within its methods.
⯈ Example
1 const student = {
2 name: 'Raj',
3 marks: 85,
4
5 getResult() {
6 // 'this' refers to the student object
7 if ([Link] >= 50) {
8 return [Link] + ' has Passed!';
9 }
10 return [Link] + ' has Failed.';
11 }
12 };
13
14 [Link]([Link]()); // Raj has Passed!
1. Selecting Elements
Definition: Selecting — Finding an HTML element using JavaScript so you can read or change it.
⯈ Common selection methods
1 // Select by ID — returns ONE element
2 const title = [Link]("title");
3
4 // Select by CSS selector — returns FIRST match
5 const para = [Link]("p");
6 const btn = [Link](".btn");
7 const header = [Link]("#header");
8
9 // Select ALL matching elements
10 const allParas = [Link]("p");
11 const allCards = [Link](".card");
12
13 // Loop through all selected elements
14 [Link](para => {
15 [Link]([Link]);
16 });
3. Changing Styles
⯈ Example
1 const box = [Link](".box");
2
3 // Change CSS style directly
4 [Link] = 'blue';
5 [Link] = '200px';
6 [Link] = '20px';
7
8 // Better way — use CSS classes
9 [Link]('active'); // add a class
10 [Link]('hidden'); // remove a class
11 [Link]('highlight'); // add if missing, remove if present
12 [Link]('active'); // returns true or false
5. Removing Elements
⯈ Example
1 const item = [Link](".item");
2
3 // Modern way
4 [Link]();
5
6 // Old way (remove a child from its parent)
7 [Link](item);
6. Working with Attributes
⯈ Example
1 // HTML: <img id='photo' src='[Link]' alt='A photo'>
2
3 const img = [Link]("photo");
4
5 // Read attribute
6 [Link]([Link]('src')); // [Link]
7
8 // Set attribute
9 [Link]('src', '[Link]');
10
11 // Remove attribute
12 [Link]('alt');
13
14 // data-* attributes
15 // HTML: <div data-user-id='42'>
16 const div = [Link]('div');
17 [Link]([Link]); // '42'
11. Events
Definition: Event — An action that happens in the browser — like a user clicking a button, typing in a
field, or moving the mouse. JavaScript can 'listen' for these events and run code when they happen.
4. preventDefault()
Definition: preventDefault() — Stops the browser's default action for an event. For example, it stops a
form from submitting or a link from navigating.
⯈ Stop form from submitting
1 // HTML: <form id="myForm"> <button type="submit">Submit</button> </form>
2
3 const form = [Link]("myForm");
4
5 [Link]('submit', function(e) {
6 [Link](); // stops the page from reloading
7 [Link]("Form submitted without page reload!");
8 // Now you can validate and send data manually
9 });
5. Event Bubbling
Definition: Event Bubbling — When an event fires on an element, it also fires on all its parent
elements, bubbling up to the top. Like a bubble rising through water.
⯈ Example
1 // HTML: <div id='parent'> <button id='child'>Click</button> </div>
2
3 [Link]("child").addEventListener("click", () => {
4 [Link]("Child clicked");
5 });
6
7 [Link]("parent").addEventListener("click", () => {
8 [Link]("Parent also fires!");
9 });
10
11 // Clicking the button outputs:
12 // Child clicked
13 // Parent also fires! (due to bubbling)
14
15 // Stop bubbling with stopPropagation()
16 [Link]("child").addEventListener("click", (e) => {
17 [Link](); // parent won't fire
18 [Link]("Only child fires");
19 });
6. Event Delegation
Definition: Event Delegation — Instead of adding listeners to every child element, add ONE listener
to the parent. It uses bubbling to catch events from children. Great for dynamic content.
⯈ Example
1 // HTML: <ul id="list"> <li>Item 1</li> <li>Item 2</li> </ul>
2
3 // Add ONE listener to the parent ul
4 const list = [Link]("list");
5
6 [Link]('click', function(e) {
7 // Check if a li was clicked
8 if ([Link] === 'LI') {
9 [Link]('You clicked:', [Link]);
10 [Link] = 'red';
11 }
12 });
13
14 // This even works for li elements added later!
12. ES6+ Modern JavaScript Features
Definition: ES6 (ECMAScript 2015) — A major update to JavaScript released in 2015 that added
many powerful features. It is the most important JavaScript upgrade. Features like let, const, arrow
functions, and Promises all came from ES6.
1. Template Literals
Definition: Template Literal — A better way to write strings using backticks (`). You can embed
expressions inside ${} and write multi-line strings easily.
⯈ Example
1 const name = "Alice";
2 const score = 95;
3
4 // Old way:
5 const msg1 = "Hello " + name + "! Your score is " + score;
6
7 // New way with template literal:
8 const msg2 = `Hello ${name}! Your score is ${score}.`;
9 [Link](msg2); // Hello Alice! Your score is 95.
10
11 // Multi-line string
12 const poem = `Roses are red,
13 Violets are blue,
14 JavaScript is fun,
15 And so are you!`;
16 [Link](poem);
Set
Definition: Set — A collection of UNIQUE values. Duplicates are automatically removed.
⯈ Example
1 const set = new Set([1, 2, 3, 2, 1, 3]);
2 [Link]([Link]); // 3 (duplicates removed)
3 [Link]([...set]); // [1, 2, 3]
4
5 // Real use case: remove duplicates from array
6 const arr = [5, 3, 5, 1, 3, 2];
7 const unique = [...new Set(arr)];
8 [Link](unique); // [5, 3, 1, 2]
13. Asynchronous JavaScript
Definition: Asynchronous — Code that runs independently without blocking other code. Instead of
waiting for a slow task (like loading data from a server), JavaScript starts it and moves on, then handles
the result when it is ready.
Synchronous vs Asynchronous
⯈ Synchronous (blocking) — one by one
1 [Link]('Step 1');
2 [Link]('Step 2');
3 [Link]('Step 3');
4 // Output: Step 1 Step 2 Step 3 (in order)
⯈ Asynchronous — non-blocking
1 [Link]('Step 1');
2
3 setTimeout(() => {
4 [Link]('Step 2 — after 2 seconds');
5 }, 2000);
6
7 [Link]('Step 3 — runs immediately');
8
9 // Output:
10 // Step 1
11 // Step 3 (does not wait!)
12 // Step 2 (appears 2 seconds later)
1. Callbacks
Definition: Callback — A function passed as an argument to another function, to be called later when
a task completes.
⯈ Simple callback
1 function downloadFile(url, onComplete) {
2 [Link]('Downloading...');
3 setTimeout(() => {
4 // After 2 seconds, call the callback with the result
5 onComplete('File downloaded!');
6 }, 2000);
7 }
8
9 downloadFile('[Link]/file', function(result) {
10 [Link](result); // File downloaded!
11 });
12
13 [Link]('This runs while downloading...');
WARNING Nesting many callbacks creates 'Callback Hell' — deeply indented code that is hard to read. Use
Promises or async/await instead.
Promise States
State Meaning Next Step
Pending The operation is still in progress Wait...
Fulfilled The operation completed successfully .then() runs
Rejected The operation failed .catch() runs
Creating a Promise
⯈ Example
1 const promise = new Promise((resolve, reject) => {
2 // Do some async work...
3 const success = true;
4
5 if (success) {
6 resolve('Data loaded!'); // fulfilled
7 } else {
8 reject('Error occurred!'); // rejected
9 }
10 });
11
12 // Use the promise
13 promise
14 .then(result => [Link](result)) // Data loaded!
15 .catch(error => [Link](error)) // Error occurred!
16 .finally(() => [Link]('Done')); // always runs