0% found this document useful (0 votes)
2 views34 pages

JavaScript Notes

Uploaded by

rosacaroh156
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views34 pages

JavaScript Notes

Uploaded by

rosacaroh156
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript Complete Study Notes

JavaScript
Complete Study Notes
From Fundamentals to Advanced Concepts

Topics Covered:
• Variables, Data Types & Operators
• Control Flow & Functions
• Arrays & Objects
• DOM Manipulation & Events
• Asynchronous JavaScript (Promises, Async/Await)
• ES6+ Modern Features
• Object-Oriented Programming
• Error Handling & Modules
• Browser APIs & Storage
• Best Practices & Common Patterns

Page
JavaScript Complete Study Notes

1. Introduction to JavaScript
JavaScript (JS) is a lightweight, interpreted, high-level programming language primarily used to
make web pages interactive. It is one of the three core technologies of the Web alongside
HTML and CSS.

1.1 Key Characteristics


• Interpreted (no compilation step needed)
• Dynamically typed (variable types are determined at runtime)
• Single-threaded with an event loop for asynchronous operations
• Prototype-based object orientation
• First-class functions (functions treated as values)
• Runs in browsers and on servers ([Link])

Note: Despite the name, JavaScript has no direct relation to Java. It was created by Brendan Eich in
1995 and standardized as ECMAScript (ES). The latest widely-used version is ES2023+.

1.2 Adding JavaScript to HTML


<!-- Inline (avoid for large scripts) -->
<script>alert("Hello!");</script>

<!-- External file (recommended) -->


<script src="[Link]" defer></script>

<!-- Module (ES6+) -->


<script type="module" src="[Link]"></script>

Page
JavaScript Complete Study Notes

2. Variables & Data Types


2.1 Variable Declarations
Keyword Description
var Function-scoped, hoisted, can be re-declared (legacy, avoid)
let Block-scoped, not hoisted to value, can be reassigned
const Block-scoped, cannot be reassigned (preferred for constants)

var x = 10; // Legacy - avoid


let name = 'Alice'; // Reassignable
const PI = 3.14159; // Constant - cannot reassign

// const with objects - reference is fixed, contents can change


const obj = { a: 1 };
obj.a = 99; // OK - mutating property
// obj = {}; // ERROR - cannot reassign reference

2.2 Primitive Data Types


Type Example / Notes
String 'hello', "world", `template`
Number 42, 3.14, NaN, Infinity
Boolean true, false
undefined Variable declared but not assigned
null Intentional absence of a value
Symbol Unique identifier (ES6+)
BigInt Integers larger than 2^53 - 1 (ES2020+)

2.3 Type Checking & Conversion


typeof 42 // 'number'
typeof 'hello' // 'string'
typeof true // 'boolean'
typeof undefined // 'undefined'
typeof null // 'object' (historical bug!)
typeof {} // 'object'
typeof [] // 'object'
typeof function(){} // 'function'

Page
JavaScript Complete Study Notes

// Explicit conversions
Number('42') // 42
String(42) // '42'
Boolean(0) // false
Boolean('hello') // true
parseInt('42px') // 42
parseFloat('3.14') // 3.14

// Implicit coercion (be careful!)


'5' + 3 // '53' (string concatenation)
'5' - 3 // 2 (numeric subtraction)

Page
JavaScript Complete Study Notes

3. Operators
3.1 Arithmetic Operators
let a = 10, b = 3;
a + b // 13 (addition)
a - b // 7 (subtraction)
a * b // 30 (multiplication)
a / b // 3.33... (division)
a % b // 1 (modulus / remainder)
a ** b // 1000 (exponentiation, ES7+)
a++ // post-increment
++a // pre-increment

3.2 Comparison Operators


// Strict equality (recommended - checks type AND value)
5 === 5 // true
5 === '5' // false
5 !== '5' // true

// Loose equality (performs type coercion - avoid)


5 == '5' // true (coerces '5' to 5)
null == undefined // true

// Relational
5 > 3 // true
5 >= 5 // true
3 < 5 // true
3 <= 2 // false

3.3 Logical & Special Operators


// Logical
true && false // false (AND)
true || false // true (OR)
!true // false (NOT)

// Nullish coalescing (ES2020) - returns right if left is null/undefined


null ?? 'default' // 'default'
0 ?? 'default' // 0 (0 is not null/undefined!)

// Optional chaining (ES2020) - safe property access


const user = null;
user?.name // undefined (no error)
user?.address?.city // undefined

// Ternary operator

Page
JavaScript Complete Study Notes

const age = 20;


const status = age >= 18 ? 'Adult' : 'Minor';

// Spread operator
const arr = [1, 2, 3];
const copy = [...arr, 4, 5]; // [1, 2, 3, 4, 5]

Page
JavaScript Complete Study Notes

4. Control Flow
4.1 Conditional Statements
// if / else if / else
const score = 85;
if (score >= 90) {
[Link]('A grade');
} else if (score >= 80) {
[Link]('B grade');
} else {
[Link]('Below B');
}

// switch
const day = 'Monday';
switch (day) {
case 'Monday':
case 'Tuesday':
[Link]('Weekday');
break;
case 'Saturday':
case 'Sunday':
[Link]('Weekend');
break;
default:
[Link]('Unknown');
}

4.2 Loops
// for loop
for (let i = 0; i < 5; i++) {
[Link](i); // 0 1 2 3 4
}

// while loop
let count = 0;
while (count < 3) {
[Link](count++);
}

// do...while (executes at least once)


let num = 10;
do {
[Link](num);
num--;
} while (num > 0);

// for...of (iterate over iterable values)

Page
JavaScript Complete Study Notes

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


for (const fruit of fruits) {
[Link](fruit);
}

// for...in (iterate over object keys)


const person = { name: 'Alice', age: 30 };
for (const key in person) {
[Link](key, person[key]);
}

// Loop control
break; // exit loop entirely
continue; // skip to next iteration

Page
JavaScript Complete Study Notes

5. Functions
5.1 Function Declarations & Expressions
// Function declaration (hoisted)
function greet(name) {
return 'Hello, ' + name + '!';
}

// Function expression (not hoisted)


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

// Arrow function (ES6) - shorter syntax


const multiply = (a, b) => a * b;

// Arrow with block body


const square = (n) => {
const result = n * n;
return result;
};

// Single parameter - parentheses optional


const double = n => n * 2;

5.2 Parameters & Arguments


// Default parameters
function power(base, exp = 2) {
return base ** exp;
}
power(3); // 9 (uses default exp = 2)
power(3, 3); // 27

// Rest parameters (collects remaining args)


function sum(...numbers) {
return [Link]((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); // 10

// Destructuring parameters
function display({ name, age }) {
[Link](`${name} is ${age} years old`);
}
display({ name: 'Bob', age: 25 });

Page
JavaScript Complete Study Notes

5.3 Closures & Higher-Order Functions


// Closure - inner function remembers outer scope
function makeCounter() {
let count = 0;
return function() {
return ++count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2
counter(); // 3

// Higher-order functions (accept/return functions)


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

// map - transforms each element


const doubled = [Link](n => n * 2); // [2,4,6,8,10]

// filter - keeps matching elements


const evens = [Link](n => n % 2 === 0); // [2,4]

// reduce - accumulates a single value


const total = [Link]((acc, n) => acc + n, 0); // 15

// Chaining
const result = numbers
.filter(n => n > 2)
.map(n => n * 10); // [30, 40, 50]

Page
JavaScript Complete Study Notes

6. Arrays
6.1 Creating & Accessing Arrays
const arr = [10, 20, 30, 40, 50];
arr[0] // 10 (first element)
arr[[Link] - 1] // 50 (last element)
[Link] // 5

// Destructuring
const [first, second, ...rest] = arr;
// first=10, second=20, rest=[30,40,50]

6.2 Common Array Methods


Method Description
push(...items) Add to end; returns new length
pop() Remove from end; returns removed element
unshift(...items) Add to beginning; returns new length
shift() Remove from beginning; returns removed element
splice(i, n, ...) Remove/replace n items at index i
slice(start, end) Returns shallow copy of portion
indexOf(val) Returns first index of val, or -1
includes(val) Returns true if val exists
find(fn) Returns first matching element
findIndex(fn) Returns index of first match
some(fn) Returns true if any element matches
every(fn) Returns true if all elements match
flat(depth) Flattens nested arrays
flatMap(fn) Maps then flattens one level
sort(fn) Sorts array in-place
reverse() Reverses array in-place
join(sep) Joins array to string
[Link]() Creates array from iterable/object
[Link]() Checks if value is an array

Page
JavaScript Complete Study Notes

const nums = [3, 1, 4, 1, 5, 9, 2, 6];

// Sort numbers correctly (default sort is alphabetical!)


[Link]((a, b) => a - b); // [1,1,2,3,4,5,6,9]

// Find and findIndex


const found = [Link](n => n > 4); // 5
const idx = [Link](n => n > 4); // index of 5

// Spread to copy (avoid mutation)


const copy = [...nums];

// Array from Set (remove duplicates)


const unique = [...new Set([1, 2, 2, 3, 3])]; // [1,2,3]

Page
JavaScript Complete Study Notes

7. Objects
7.1 Creating & Accessing Objects
// Object literal
const person = {
name: 'Alice',
age: 30,
greet() {
return `Hi, I'm ${[Link]}`;
}
};

// Dot notation
[Link] // 'Alice'

// Bracket notation (useful for dynamic keys)


const key = 'age';
person[key] // 30

// Destructuring
const { name, age, city = 'Unknown' } = person;
// name='Alice', age=30, city='Unknown' (default)

// Renamed destructuring
const { name: fullName } = person; // fullName='Alice'

7.2 Object Methods


const obj = { a: 1, b: 2, c: 3 };

[Link](obj) // ['a', 'b', 'c']


[Link](obj) // [1, 2, 3]
[Link](obj) // [['a',1], ['b',2], ['c',3]]

// Merge / shallow clone


const merged = [Link]({}, obj, { d: 4 });
const spread = { ...obj, d: 4 }; // same result

// Deep clone (simple objects)


const deep = [Link]([Link](obj));

// Check property existence


'a' in obj // true
[Link]('a') // true

// Freeze (prevent modifications)


const frozen = [Link]({ x: 1 });
frozen.x = 99; // silently ignored (or error in strict mode)

Page
JavaScript Complete Study Notes

Page
JavaScript Complete Study Notes

8. Strings
8.1 String Creation & Template Literals
const s1 = 'single quotes';
const s2 = "double quotes";
const name = 'World';
const s3 = `Hello, ${name}!`; // template literal (ES6)

// Multi-line template literal


const html = `
<div>
<p>${name}</p>
</div>
`;

8.2 Common String Methods


Method Description
length Number of characters
toUpperCase() Convert to uppercase
toLowerCase() Convert to lowercase
trim() Remove whitespace from both ends
trimStart() / trimEnd() Remove whitespace from one end
includes(sub) Check if substring exists
startsWith(sub) Check prefix
endsWith(sub) Check suffix
indexOf(sub) First index of substring
lastIndexOf(sub) Last index of substring
slice(start, end) Extract portion
substring(start, end) Similar to slice
replace(old, new) Replace first occurrence
replaceAll(old, new) Replace all occurrences
split(sep) Split into array
padStart(len, char) Pad beginning to length
padEnd(len, char) Pad end to length
repeat(n) Repeat string n times

Page
JavaScript Complete Study Notes

charAt(i) Character at index


charCodeAt(i) UTF-16 code at index
at(i) Character at index (supports negative)

Page
JavaScript Complete Study Notes

9. DOM Manipulation
9.1 Selecting Elements
// Single element selectors
[Link]('myId')
[Link]('.myClass') // CSS selector, first match
[Link]('#myId > p')

// Multiple element selectors (returns NodeList)


[Link]('.item') // static NodeList
[Link]('item') // live HTMLCollection
[Link]('div') // live HTMLCollection

// Convert NodeList to Array for array methods


const items = [...[Link]('.item')];

9.2 Modifying Elements


const el = [Link]('#box');

// Content
[Link] = 'New text'; // plain text (safe)
[Link] = '<strong>Bold</strong>'; // HTML (XSS risk!)

// Attributes
[Link]('data-id', '42');
[Link]('data-id'); // '42'
[Link]('data-id');
[Link] = 'newId';
[Link] = '[Link]';

// CSS Classes
[Link]('active');
[Link]('hidden');
[Link]('open');
[Link]('active'); // true/false
[Link]('old', 'new');

// Inline styles
[Link] = 'red';
[Link] = '#fff';
[Link] = 'none';

9.3 Creating & Removing Elements


// Create new elements
const div = [Link]('div');

Page
JavaScript Complete Study Notes

[Link] = 'Hello!';
[Link] = 'card';

// Insert into DOM


[Link](div);
[Link](div);
[Link](div, referenceNode);
[Link](div); // modern, accepts text too
[Link](div); // insert before
[Link](div); // insert after

// Remove elements
[Link](); // modern
[Link](el); // legacy

// Clone
const clone = [Link](true); // deep clone

Page
JavaScript Complete Study Notes

10. Events
10.1 Adding & Removing Event Listeners
const btn = [Link]('#myBtn');

// Add listener
[Link]('click', function(event) {
[Link]('Clicked!', event);
});

// Arrow function (this is not bound)


[Link]('mouseover', (e) => {
[Link] = 'blue';
});

// Named function - can be removed


function handleClick(e) { [Link]('Click'); }
[Link]('click', handleClick);
[Link]('click', handleClick);

// Once option (fires only once)


[Link]('click', fn, { once: true });

10.2 Common Event Types


Event Description
click Element clicked
dblclick Element double-clicked
mouseover / mouseout Mouse enters/leaves element
mouseenter / mouseleave Mouse enters/leaves (no bubbling)
keydown / keyup Key pressed / released
keypress Key pressed (deprecated)
input Input value changes
change Input value changes and loses focus
submit Form submitted
focus / blur Element gains/loses focus
load Page/resource fully loaded
DOMContentLoaded DOM parsed (before images load)
resize Window resized

Page
JavaScript Complete Study Notes

scroll Page scrolled


contextmenu Right-click context menu

10.3 Event Object & Delegation


// Event object properties
[Link]('click', (e) => {
[Link] // element that was clicked
[Link] // element listener is attached to
[Link] // 'click'
[Link], [Link] // mouse coordinates
[Link] // key pressed (keyboard events)
[Link]() // stop default behavior (e.g. form submit)
[Link]() // stop bubbling
});

// Event delegation (efficient - one listener for many children)


[Link]('#list').addEventListener('click', (e) => {
if ([Link]('[Link]')) {
[Link]('List item clicked:', [Link]);
}
});

Page
JavaScript Complete Study Notes

11. Asynchronous JavaScript


11.1 Callbacks
// Traditional callback pattern
function fetchData(url, callback) {
setTimeout(() => {
const data = { id: 1, name: 'Alice' };
callback(null, data); // (error, result) convention
}, 1000);
}

fetchData('api/user', (err, data) => {


if (err) { [Link](err); return; }
[Link](data);
});

// Callback hell (pyramid of doom) - avoid!


getData(function(a) {
getMoreData(a, function(b) {
getEvenMoreData(b, function(c) { ... });
});
});

11.2 Promises
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve('Data loaded!');
} else {
reject(new Error('Loading failed'));
}
});

// Consuming a Promise
myPromise
.then(data => [Link](data)) // 'Data loaded!'
.catch(err => [Link](err))
.finally(() => [Link]('Done'));

// Promise combinators
[Link]([p1, p2, p3]) // all must resolve
[Link]([p1, p2]) // wait for all (any outcome)
[Link]([p1, p2]) // first to settle wins
[Link]([p1, p2]) // first to resolve wins

Page
JavaScript Complete Study Notes

11.3 Async / Await (ES2017+)


// async function always returns a Promise
async function loadUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (![Link]) throw new Error('Not found');
const user = await [Link]();
return user;
} catch (error) {
[Link]('Error:', [Link]);
}
}

// Usage
const user = await loadUser(1); // inside async context
loadUser(1).then(u => [Link](u)); // outside async

// Parallel execution (don't await sequentially!)


const [users, posts] = await [Link]([
fetch('/api/users').then(r => [Link]()),
fetch('/api/posts').then(r => [Link]())
]);

Best Practice: Always use try/catch with async/await. Prefer [Link]() for parallel operations
instead of awaiting sequentially, which is much slower.

Page
JavaScript Complete Study Notes

12. ES6+ Modern Features


12.1 Destructuring
// Array destructuring
const [a, b, ...rest] = [1, 2, 3, 4, 5];
// a=1, b=2, rest=[3,4,5]

// Skip elements
const [,, third] = [10, 20, 30]; // third=30

// Object destructuring with defaults


const { name = 'Anonymous', age = 0, city } = user;

// Nested destructuring
const { address: { street, zip } } = user;

// In function parameters
function greet({ name, greeting = 'Hello' }) {
return `${greeting}, ${name}!`;
}

12.2 Spread & Rest Operators


// Spread - expands iterables
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1,2,3,4,5,6]

// Spread in function calls


[Link](...arr1); // 3

// Object spread (shallow merge)


const defaults = { color: 'blue', size: 'md' };
const custom = { ...defaults, color: 'red' };
// { color: 'red', size: 'md' }

// Rest - collect remaining


function log(first, ...others) {
[Link](first); // first argument
[Link](others); // array of remaining
}

12.3 Map, Set, WeakMap, WeakSet


// Map - key/value with any key type
const map = new Map();

Page
JavaScript Complete Study Notes

[Link]('name', 'Alice');
[Link](42, 'answer');
[Link]('name'); // 'Alice'
[Link](42); // true
[Link]; // 2
[Link]('name');
for (const [key, val] of map) { ... }

// Set - unique values only


const set = new Set([1, 2, 2, 3, 3]);
[Link]; // 3
[Link](4);
[Link](2); // true
[Link](2);
const arr = [...set]; // convert to array

// Remove duplicates from array


const unique = [...new Set([1, 2, 2, 3])]; // [1,2,3]

12.4 Symbols & Iterators


// Symbol - unique, immutable identifier
const sym1 = Symbol('description');
const sym2 = Symbol('description');
sym1 === sym2; // false (always unique)

// Well-known Symbols
[Link] // define custom iteration
[Link] // custom type conversion

// Custom iterator
const range = {
from: 1, to: 5,
[[Link]]() {
let current = [Link];
const last = [Link];
return {
next() {
return current <= last
? { value: current++, done: false }
: { done: true };
}
};
}
};
[Link]([...range]); // [1, 2, 3, 4, 5]

Page
JavaScript Complete Study Notes

13. Object-Oriented Programming


13.1 Classes (ES6+)
class Animal {
// Private field (ES2022)
#name;

constructor(name, sound) {
this.#name = name;
[Link] = sound;
}

// Instance method
speak() {
return `${this.#name} says ${[Link]}!`;
}

// Getter / Setter
get name() { return this.#name; }
set name(val) {
if (typeof val !== 'string') throw new Error('Invalid');
this.#name = val;
}

// Static method (on class, not instance)


static create(name, sound) {
return new Animal(name, sound);
}
}

// Inheritance
class Dog extends Animal {
constructor(name) {
super(name, 'Woof'); // call parent constructor
[Link] = [];
}

learn(trick) {
[Link](trick);
}

// Override parent method


speak() {
return [Link]() + ' *wags tail*';
}
}

const dog = new Dog('Rex');


[Link](); // 'Rex says Woof! *wags tail*'
dog instanceof Dog; // true
dog instanceof Animal; // true

Page
JavaScript Complete Study Notes

13.2 Prototypes
// Every object has a prototype chain
function Person(name) {
[Link] = name;
}
[Link] = function() {
return 'Hi, I am ' + [Link];
};

const alice = new Person('Alice');


[Link](); // 'Hi, I am Alice'

// [Link]() - set prototype explicitly


const animal = { breathe() { return 'breathing'; } };
const dog = [Link](animal);
[Link] = function() { return 'woof'; };
[Link](); // works via prototype chain

// Check prototype
[Link](dog) === animal; // true

Page
JavaScript Complete Study Notes

14. Error Handling


14.1 try / catch / finally
try {
const result = [Link]('{invalid json}');
} catch (error) {
[Link]([Link]); // 'SyntaxError'
[Link]([Link]); // detailed message
[Link]([Link]); // stack trace
} finally {
[Link]('Always runs'); // cleanup code
}

// Custom errors
class ValidationError extends Error {
constructor(message, field) {
super(message);
[Link] = 'ValidationError';
[Link] = field;
}
}

function validate(user) {
if (![Link]) {
throw new ValidationError('Name is required', 'name');
}
}

try {
validate({});
} catch (e) {
if (e instanceof ValidationError) {
[Link](`Field: ${[Link]}, Error: ${[Link]}`);
} else {
throw e; // re-throw unexpected errors
}
}

14.2 Error Types


Error Type Description
Error Generic error base class
SyntaxError Invalid JavaScript syntax
TypeError Wrong type (e.g., [Link])
ReferenceError Accessing undefined variable
RangeError Value out of allowed range

Page
JavaScript Complete Study Notes

URIError Invalid URI encoding/decoding


EvalError Error in eval() (rare)

Page
JavaScript Complete Study Notes

15. Modules (ES6)


15.1 Named & Default Exports
// [Link] - Named exports
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }

// [Link] - Default export


export default class User {
constructor(name) { [Link] = name; }
}

// Re-export
export { add, multiply } from './[Link]';

15.2 Importing
// Named imports
import { PI, add, multiply } from './[Link]';

// Rename imports
import { add as sum } from './[Link]';

// Default import (any name)


import User from './[Link]';

// Mix default and named


import User, { PI } from './[Link]';

// Namespace import
import * as Math from './[Link]';
[Link](1, 2); // 3

// Dynamic import (lazy loading)


const module = await import('./[Link]');
[Link]();

Page
JavaScript Complete Study Notes

16. Browser APIs & Storage


16.1 Timers
// setTimeout - execute once after delay
const timer = setTimeout(() => {
[Link]('Runs after 2 seconds');
}, 2000);
clearTimeout(timer); // cancel before firing

// setInterval - execute repeatedly


const interval = setInterval(() => {
[Link]('Runs every second');
}, 1000);
clearInterval(interval); // stop repeating

// requestAnimationFrame - for smooth animations


function animate() {
// update animation frame
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

16.2 Web Storage


// localStorage (persists across sessions)
[Link]('user', [Link]({ name: 'Alice' }));
const user = [Link]([Link]('user'));
[Link]('user');
[Link](); // remove all

// sessionStorage (clears when tab closes)


[Link]('token', 'abc123');
[Link]('token');

// Cookies (more complex, sent with requests)


[Link] = 'name=Alice; max-age=3600; path=/';
[Link]; // read all cookies as string

16.3 Fetch API


// GET request
const response = await fetch('[Link]
const users = await [Link]();

// POST request with JSON body


const response = await fetch('/api/users', {
method: 'POST',

Page
JavaScript Complete Study Notes

headers: { 'Content-Type': 'application/json' },


body: [Link]({ name: 'Alice', age: 30 })
});

if (![Link]) {
throw new Error(`HTTP error! status: ${[Link]}`);
}
const newUser = await [Link]();

// Response types
[Link]() // parse JSON
[Link]() // get text
[Link]() // binary data
[Link]() // form data

Page
JavaScript Complete Study Notes

17. Best Practices & Common Patterns


17.1 Code Quality
• Always use const by default; use let only when reassignment is needed; never use var
• Use === (strict equality) instead of == to avoid unexpected type coercion
• Use optional chaining (?.) and nullish coalescing (??) to handle null/undefined safely
• Keep functions small and focused on a single responsibility (Single Responsibility
Principle)
• Use descriptive, meaningful names for variables and functions
• Always handle errors in Promises and async/await with try/catch
• Avoid modifying function arguments directly; prefer returning new values

17.2 Performance Tips


• Cache DOM queries in variables rather than querying the DOM repeatedly
• Use event delegation instead of attaching listeners to many individual elements
• Debounce or throttle expensive event handlers (scroll, resize, input)
• Use DocumentFragment for batch DOM insertions to minimize reflows
• Lazy-load modules with dynamic import() for better initial load time
• Avoid deeply nested loops; prefer flat data structures and efficient algorithms

17.3 Common Patterns


Module Pattern
const Counter = (() => {
let count = 0; // private
return {
increment() { count++; },
decrement() { count--; },
getCount() { return count; }
};
})();

[Link]();
[Link](); // 1

Observer Pattern
class EventEmitter {
#events = {};

on(event, listener) {
(this.#events[event] ||= []).push(listener);

Page
JavaScript Complete Study Notes

off(event, listener) {
this.#events[event] = (this.#events[event] || [])
.filter(l => l !== listener);
}

emit(event, ...args) {
(this.#events[event] || []).forEach(l => l(...args));
}
}

Debounce & Throttle


// Debounce - delay execution until after user stops
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => [Link](this, args), delay);
};
}

// Throttle - limit to once per time window


function throttle(fn, limit) {
let lastCall = 0;
return function(...args) {
const now = [Link]();
if (now - lastCall >= limit) {
lastCall = now;
[Link](this, args);
}
};
}

// Usage
const onSearch = debounce((query) => search(query), 300);
[Link]('input', (e) => onSearch([Link]));

Page
JavaScript Complete Study Notes

18. Quick Reference Cheat Sheet


Key Concepts Summary
Concept Notes
var / let / const Variable declarations (prefer const > let > var)
=== !== Strict equality / inequality (always use these)
?. ?? Optional chaining / Nullish coalescing (ES2020)
...spread Expand arrays/objects into individual elements
...rest Collect remaining arguments into an array
Arrow fn => Compact functions; lexically binds 'this'
Template literals String interpolation: `Hello ${name}`
Destructuring Unpack arrays/objects: const {a,b} = obj
Promise Represents future value; .then().catch().finally()
async/await Syntactic sugar for Promises; use try/catch
class/extends ES6 OOP with inheritance; super() for parent
import/export ES6 module system for code organization
Map / Set Key-value and unique-value collections
Symbol Unique, immutable primitive for identifiers
Proxy / Reflect Intercept and customize object operations
WeakMap / WeakSet Like Map/Set but allow garbage collection
Generator function* Lazily produce sequences with yield
localStorage Persistent client-side storage (string only)
fetch() Modern HTTP request API returning Promises
setTimeout Delay code execution; clearTimeout to cancel

Study Tip: Practice these concepts by building small projects. Combining DOM manipulation, events,
fetch API, and async/await covers the majority of real-world JavaScript patterns.

Page

You might also like