Created by Mahmood Damra
Spread ... expands arrays/objects. Rest ... collects remaining items.
Spread: copy, merge, pass as arguments. Rest: flexible function parameters.
// Spread
const arr2 = [...arr1, 4, 5];
const obj2 = { ...obj1, newProp: true };
// Rest
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
Use Case: Immutable updates, flexible functions, merging data.
reduce is the most powerful array method.
Can transform array into ANY shape: number, string, object, array.
Accumulator pattern: start with initial value, build up result.
const votes = ['yes','no','yes','yes','no'];
const tally = votes.reduce((acc, vote) => {
acc[vote] = (acc[vote] || 0) + 1;
return acc;
}, {});
// { yes: 3, no: 2 }
Use Case: Counting, grouping, transforming data structures.
classList.add/remove/toggle/contains('class')
Direct style: element.style.property = value Computed style: getComputedStyle(el)
Prefer classList over direct style manipulation!
modal.classList.toggle('hidden');
btn.classList.add('active');
// Direct style (use sparingly)
element.style.display = 'none';
element.style.backgroundColor = '#fff';Use Case: Showing/hiding modals, toggling themes, dynamic styling.
try/catch/finally — handle runtime errors gracefully. throw new Error('message') — create custom errors.
Debugging tools: • console.log(), console.table() • Browser DevTools debugger • debugger statement in code
try {
const data = JSON.parse(rawInput);
if (!data.name) throw new Error('Name required');
} catch (err) {
console.error('Parse failed:', err.message);
} finally {
hideLoadingSpinner();
}Use Case: Robust apps that don't crash on bad data.
HTML elements nest inside each other like Russian dolls. Proper nesting = valid HTML.
Every HTML file needs: <!DOCTYPE html>, <html>, <head>, <body>
<!DOCTYPE html>
<html lang='en'>
<head><title>My Site</title></head>
<body><h1>Hello</h1></body>
</html>
Use Case: The boilerplate you write for every new webpage.
Tags are the building blocks. Opening <tag> and closing </tag> wrap content.
Block elements: <h1>, <p>, <div>, <ul> Inline elements: <span>, <a>, <strong>, <em>
<h1>My Page</h1>
<p>Hello <strong>world</strong></p>
Use Case: Every webpage starts with HTML tags.
Named exports: multiple per file Default export: one per file
Modules keep code organized and reusable. Each file is its own scope.
// utils.js
export const formatDate = (d) => d.toLocaleDateString();
export default class API { }
// app.js
import API, { formatDate } from './utils.js';
Use Case: Code organization, separation of concerns.
.map() transforms every element → new array. .join(separator) converts array to string.
Perfect combo for generating HTML from data!
const names = ['Alice', 'Bob', 'Charlie'];
const html = names
.map(name => `<li>${name}</li>`)
.join('');
// '<li>Alice</li><li>Bob</li><li>Charlie</li>'
Use Case: Rendering lists in React, building HTML strings.
submit event — form submitted input event — any change in real-time change event — after leaving field
HTML validation attributes: required, minlength, maxlength, pattern, type='email'
form.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(form);
const data = Object.fromEntries(formData);
console.log(data); // { name: 'Alice', email: '...' }
});Use Case: Login forms, registration, search, contact forms.
<img> TagEmbeds images. Self-closing tag with src and alt attributes.
alt is critical for accessibility — screen readers use it to describe images.
<img src='photo.jpg' alt='A sunset over mountains' />
Use Case: Displaying photos, logos, icons on your page.
<button> creates clickable buttons. <input> creates text fields, checkboxes, radio buttons.
The type attribute controls what kind of input: text, email, password, checkbox, radio
<button>Click me</button>
<input type='text' placeholder='Name' />
<input type='email' placeholder='Email' />
Use Case: Building forms, search bars, login pages.
forEach, map, filter, reduce, find — the big five.
.map() vs .forEach(): map returns a new array, forEach doesn't. .join() turns array into string. .includes() checks if item exists.
<header> = introductory content or navigation. <nav> = navigation links. <main> = dominant content, unique to this page.Only ONE <main> per page. Helps screen readers jump to content.
html<header> <nav><a href='/'>Home</a></nav></header><main> <h1>Welcome</h1></main>
Use Case: Every well-structured webpage uses these three.
<a href='url'> creates hyperlinks — the backbone of the web.
target='_blank' opens in new tab. Relative paths: ./about.html Absolute paths: https://google.com
<a href='https://google.com' target='_blank'>Google</a>
<a href='./about.html'>About Us</a>
Use Case: Navigation menus, linking between pages, external references.
Handling user input in JavaScript.
<form> elements group inputs. submit event fires when form is submitted. e.preventDefault() stops page reload. FormData API reads all form values at once.
ES6+ features that make code cleaner.
Destructuring, spread/rest, modules, arrow functions, ternary operators.
Create smooth transitions between states.
transition — animate property changes. Always provide :focus styles for keyboard users!
:focus-visible — only show focus ring for keyboard nav (not mouse clicks).
.btn {
background: #3b82f6;
transition: all 0.2s ease;
}
.btn:hover { background: #2563eb; transform: translateY(-2px); }
.btn:active { transform: translateY(0); }
.btn:focus-visible { outline: 3px solid #60a5fa; }Use Case: Buttons, links, cards — any interactive element.
<section> = thematic grouping of content. <article> = self-contained content (blog post, comment). <footer> = footer info, copyright, links.
Use aria-labelledby to connect sections to their headings.
html<article> <h2>Blog Post Title</h2> <p>Content here...</p></article><footer>© 2024</footer>
Use Case: Blog layouts, news sites, any content-heavy page.
---Just copy each block into the corresponding empty node in your canvas! The backticks around the tag names will prevent Obsidian from eating them as HTML.
overflow: hidden — clip content overflow: auto — scrollbar when needed overflow-x/y — control per axis
float — legacy layout technique. Modern: use Flexbox/Grid instead. clear: both — stop floating.
.card { overflow: hidden; border-radius: 12px; }
.scroll-container { overflow-y: auto; max-height: 400px; }
/* Legacy float (avoid in new code) */
.img { float: left; margin-right: 1rem; }Use Case: Scrollable containers, image clipping, text overflow.
<ul>) use bullets. Ordered lists (<ol>) use numbers. Each item wrapped in <li>.Lists are semantic — screen readers announce 'list of 5 items'.
html<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
Use Case: Navigation menus, feature lists, steps in a process.
ARIA (Accessible Rich Internet Applications) adds extra info for assistive tech.
role='button' — tells screen readers a div acts as button. aria-label='Close menu' — provides label. aria-live='polite' — announces dynamic changes.
<div role='button' aria-label='Close' tabindex='0'>
✕
</div>
<div aria-live='polite'>3 items in cart</div>
Use Case: Making interactive elements accessible to all users.
fixed — stays visible during scroll (navbars!). sticky — normal until scroll point, then sticks.
z-index controls stacking order (higher = on top). Only works on positioned elements.
.navbar { position: fixed; top: 0; z-index: 100; }
.sidebar { position: sticky; top: 80px; }
.modal-overlay { position: fixed; z-index: 999; }Use Case: Sticky headers, fixed navbars, modal overlays.
CSS supports named colors, hex, RGB, HSL.
color = text color background-color = fill color background-image = image behind content background-size: cover = fill container opacity = transparency (0 to 1)
.hero {
background: linear-gradient(135deg, #667eea, #764ba2);
color: white;
}Use Case: Creating visually appealing sections, hero banners, cards.
Control text appearance.
font-family — which font (use Google Fonts!) font-size — how big (use rem) font-weight — bold (400=normal, 700=bold) line-height — space between lines text-align — left/center/right text-transform — uppercase/lowercase
@import url('https://fonts.googleapis.com/css2?family=Inter');
body { font-family: 'Inter', sans-serif; }
h1 { font-size: 2.5rem; font-weight: 800; }Use Case: Making text readable and beautiful.
States that change element appearance on interaction.
:hover — mouse over :focus — keyboard/click focus :active — being clicked :first-child, :nth-child() — by position ::before, ::after — insert content
Target elements to style them.
Element: p { } — all paragraphs Class: .card { } — elements with class='card' ID: #logo { } — one unique element Compound: nav a { } — links inside nav
.btn { background: blue; color: white; }
.btn:hover { background: darkblue; }
#hero { font-size: 3rem; }Use Case: Styling specific parts of your page.
position: relative on parent creates a positioning context. position: absolute on child positions it relative to that parent.
Remove from normal flow — other elements ignore it. Use top, right, bottom, left to place.
.card { position: relative; }
.badge {
position: absolute;
top: -10px;
right: -10px;
}Use Case: Badges, tooltips, dropdown menus, overlays.
10.5 hours · 121 lessons
Intermediate JS: forms, imports, advanced array methods, error handling, OOP.
Projects: Cookie Consent, Meme App, X Clone, Restaurant Ordering App
62 min · 12 lessons
HTML (HyperText Markup Language) is the skeleton of every webpage. Tags define structure, content, and meaning.
Meaningful tags for accessibility & SEO
Semantic tags tell the browser AND screen readers WHAT the content IS, not just how it looks.
<div> = generic container (no meaning) <main> = the primary content (meaningful!)
Block elements take full width, stack vertically. <div>, <p>, <h1>, <section>, <ul>
Inline elements flow with text, only take needed width. <span>, <a>, <strong>, <img>
display: inline-block = inline flow + block sizing
.tag { display: inline-block; padding: 4px 8px; }
.card { display: block; width: 100%; }Use Case: Understanding why elements stack or flow side-by-side.
Control WHERE elements appear on the page.
static — default, normal flow relative — offset from normal position absolute — positioned to nearest relative parent fixed — stays in viewport sticky — hybrid: scrolls then sticks
Combine selectors for precision.
.card .title — descendant .card > .title — direct child .card + .title — adjacent sibling .card ~ .title — general sibling .btn.primary — element with BOTH classes
/* Descendant */
nav a { color: white; }
/* Direct child only */
.menu > li { list-style: none; }
/* Both classes on same element */
.btn.danger { background: red; }
Use Case: Targeting specific elements without extra classes.
Group selectors with commas. Use BEM naming: Block__Element–Modifier.
Organize CSS: reset → base → layout → components → utilities.
h1, h2, h3 { font-family: 'Inter'; }
/* BEM naming */
.card { }
.card__title { }
.card__title--large { }
.card--featured { }Use Case: Maintainable, scalable CSS architecture.
How CSS decides which rule wins when conflicts exist.
Specificity hierarchy:
!important (avoid!)style=''#id (100 points).class (10 points)div (1 point)Margin = space OUTSIDE the element (pushes others away) Padding = space INSIDE the element (breathing room)
Shorthand: margin: top right bottom left Or: margin: 10px 20px (vertical horizontal)
⚠️ Margins collapse — two vertical margins merge into the larger one.
.card {
margin: 20px auto; /* centered */
padding: 1.5rem 2rem;
}
.section { margin-bottom: 3rem; }Use Case: Spacing elements apart and giving content room to breathe.
border: width style color border-radius rounds corners.
border-radius: 50% = perfect circle border-radius: 8px = subtle rounding
Use outline for focus states (doesn't affect layout).
.card { border: 1px solid #e2e8f0; border-radius: 12px; }
.avatar { border-radius: 50%; }
.btn:focus { outline: 3px solid blue; }Use Case: Cards, buttons, avatars, input fields.
4.4 hours · 50 lessons
Advanced selectors, specificity, positioning, layout techniques.
Projects: NFT Site, Portfolio, Coworking Space Site, Instagram Clone
77 min · 18 lessons
CSS (Cascading Style Sheets) controls how HTML looks. Colors, fonts, spacing, layout — all CSS.
Three ways to add CSS:
style='color:red'<style> in <head><link> to .css file ✅Without it: width: 200px + padding: 20px = 240px total 😱 With it: width: 200px includes padding + border = 200px total ✅
Always set this globally!
*, *::before, *::after {
box-sizing: border-box;
}
/* Now widths are predictable */Use Case: The first line in every CSS reset. Makes layout predictable.
Skip nav link — lets keyboard users skip to main content. ARIA live regions — announce dynamic content changes to screen readers.
aria-live='polite' — wait for pause aria-live='assertive' — announce immediately
<a href='#main' class='skip-link'>Skip to content</a>
<!-- ... nav ... -->
<main id='main'>
<div aria-live='polite'>
<!-- Dynamic content announced to screen readers -->
Items in cart: 3
</div>
Use Case: Making SPAs and dynamic content accessible.
The foundation of all CSS layout.
Every element is a box with 4 layers: Content → Padding → Border → Margin
box-sizing: border-box makes padding/border included in width. Always use it!
display: flex — enables flexbox flex-direction: row | column — main axis justify-content — align on main axis → center, space-between, space-around, flex-end align-items — align on cross axis → center, stretch, flex-start flex-wrap: wrap — items wrap to next line gap: 1rem — space between items
.nav {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}Use Case: Navigation bars, card grids, centering content.
Every input MUST have a label (linked via for/id). Radio buttons need <fieldset> + <legend>.
All interactive elements must be keyboard-accessible. tabindex='0' — add to tab order. Focus indicators (outline) — never remove!
<label for='email'>Email:</label>
<input id='email' type='email' required />
<fieldset>
<legend>Preferred contact:</legend>
<input type='radio' id='phone' name='contact' />
<label for='phone'>Phone</label>
</fieldset>
Use Case: Forms that everyone can fill out correctly.
Every <img> needs alt text describing the image. Decorative images: alt='' (empty, not missing!).
Links must be descriptive — never 'click here'. Link text should make sense out of context.
<img src='chart.png' alt='Sales grew 40% in Q3' />
<img src='divider.png' alt='' /> <!-- decorative -->
<!-- Bad: -->
<a href='/report'>Click here</a>
<!-- Good: -->
<a href='/report'>View Q3 Sales Report</a>
Use Case: Screen reader users understand images and navigate via links.
95 min · 23 lessons
Build websites that work for EVERYONE — including people with visual, motor, hearing, or cognitive disabilities.
~15% of the world has a disability. Accessibility isn't optional.
5.6 hours · 77 lessons
Learn to build website layouts with HTML and style them with CSS. The visual foundation of everything on the web.
One-dimensional layout: rows OR columns.
Flexbox solved 90% of CSS layout pain. Parent becomes flex container, children become flex items.
display: flex on parent = magic. Default: items line up horizontally.
flex-grow: 1 — item grows to fill space flex-shrink: 0 — item won't shrink flex-basis: 300px — starting size
Shorthand: flex: 1 = grow:1 shrink:1 basis:0% align-self — override alignment for one item order — change visual order
.sidebar { flex: 0 0 250px; } /* fixed width */
.main { flex: 1; } /* takes remaining space */Use Case: Sidebar layouts, equal-height columns, flexible cards.
WCAG contrast ratios: Normal text: 4.5:1 minimum Large text: 3:1 minimum
Never use color ALONE to convey info (colorblind users!). Use icons + color, or patterns + color.
Tools: WebAIM Contrast Checker
/* Good contrast */
.text { color: #1a1a2e; background: #f5f5f5; }
/* Don't rely only on color: */
.error { color: red; }
.error::before { content: '⚠️ '; } /* icon too! */
Use Case: Ensuring all users can read your content.
HTML · CSS · JavaScript · Tools · Accessibility
The building blocks of the web. 6 modules covering everything from your first HTML tag to DOM manipulation & ES6+.
The holy grail of CSS — centering both horizontally AND vertically.
Just 3 lines!
.container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}Use Case: Login forms, hero sections, modals, loading spinners.
Branch = isolated workspace for a feature. PR = request to merge branch into main.
git checkout -b feature/name — create & switch git merge branch — combine branches
Merge conflicts happen when same lines changed. Resolve manually.
git checkout -b feature/login
# ... make changes ...
git add . && git commit -m 'Add login'
git push origin feature/login
# Create PR on GitHub
# After review: merge into main
Use Case: Team collaboration, code review, safe feature development.
Version control = time travel for your code.
Git tracks changes locally. GitHub hosts repos online.
Branching lets you work on features without breaking main code.
2.2 hours · 16 lessons
Command line mastery and Git version control. Essential developer workflow skills.
Two-dimensional layout: rows AND columns simultaneously.
Grid is for complex page layouts. Flexbox = 1D (row or column) Grid = 2D (rows AND columns at once)
Use both! Grid for page layout, Flexbox for component layout.
display: grid — enables grid grid-template-columns — define columns grid-template-rows — define rows gap — spacing between cells
fr unit = fraction of available space repeat(3, 1fr) = three equal columns minmax(250px, 1fr) = responsive columns
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
}Use Case: Product grids, image galleries, dashboard layouts.
SSH keys = passwordless auth with GitHub. GPG keys = verify commit authorship.
Best practices: • Commit often with clear messages • Use conventional commits: feat:, fix:, docs: • Make frequent GitHub contributions • Never commit secrets/API keys!
ssh-keygen -t ed25519 -C 'email@example.com'
# Add public key to GitHub settings
# .gitignore - always create one!
node_modules/
.env
*.log
Use Case: Professional development workflow, career building.
git init — create repo git add . — stage all changes git commit -m 'msg' — save snapshot git status — check what changed git log — view history git diff — see changes git push/pull — sync with remote
git init
git add .
git commit -m 'feat: add login page'
git push origin main
# Check status anytime:
git status
git log --oneline -10
Use Case: Every developer uses Git daily.
Navigate your computer without a mouse.
Terminal/Shell/CLI — all the same concept. Bash (Mac/Linux) or PowerShell (Windows).
Faster than clicking through folders!
8.5 hours · 131 lessons
The programming language of the web. Make pages interactive, handle data, respond to users.
Projects: Counter App, Blackjack Game, Chrome Extension
Learn by building real things!
Projects in this module: • Personal Website • Digital Business Card • Space Exploration Layout • Birthday GIFt Site • 🏆 Solo: Hometown Homepage
Deploy with GitHub + Netlify.
auto-fit + minmax() = responsive without media queries!
dense packing fills gaps automatically. grid-auto-flow: dense — backfills empty cells.
Combine with span for featured items.
.gallery {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-auto-flow: dense;
}
.featured { grid-column: span 2; grid-row: span 2; }Use Case: Image galleries, masonry layouts, auto-responsive grids.
Name areas for intuitive layouts!
grid-template-areas defines a visual map. Children use grid-area: name to claim spots.
Grid lines: grid-column: 1 / 3 spans columns 1-2.
.layout {
grid-template-areas:
'header header'
'sidebar main'
'footer footer';
}
.header { grid-area: header; }Use Case: Complex page layouts, responsive dashboard shells.
Handling operations that take time.
Network requests, timers, file reads — all async.
Evolution: Callbacks → Promises → async/await
The foundation of all programming.
let — can be reassigned const — cannot be reassigned (default choice!) var — old way, avoid it
Types: String, Number, Boolean, null, undefined, Object, Array
grep 'pattern' file — search in files find . -name '*.js' — find files cat file — display file contents wc -l file — count lines sort file — sort contents kill PID — stop a process Ctrl+C — kill running command
grep -r 'TODO' src/ # find all TODOs
find . -name '*.css' # find CSS files
cat package.json | grep version
ps aux | grep node # find node processes
Use Case: Debugging, finding code, managing processes.
Arrays = ordered lists: [1, 2, 3] Objects = key-value pairs: { name: 'Alice' }
Arrays and objects are the primary data structures in JavaScript.
cd path — change directory ls / dir — list files pwd — print working directory mkdir name — create folder touch file / New-Item — create file rm file — delete file rm -rf dir — delete folder (⚠️ dangerous!) cp — copy, mv — move/rename
cd ~/projects/my-app
ls -la # list with details
mkdir components
touch index.js
cp index.js backup.js
mv old.js new.js
Use Case: Scaffolding projects, organizing files, quick operations.
The DOM (Document Object Model) is your page as a JavaScript object tree.
JS can read, modify, add, and remove HTML elements. This is how you make pages interactive!
Google Fonts — free web fonts. Add via <link> or @import.
@font-face — self-host custom fonts for better performance.
Performance tip: use font-display: swap to avoid invisible text.
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');
/* Or self-host: */
@font-face {
font-family: 'MyFont';
src: url('./fonts/myfont.woff2') format('woff2');
font-display: swap;
}Use Case: Beautiful typography without system font limitations.
Git = version control (save snapshots of code) GitHub = host your Git repos online Netlify = deploy static sites for free
Workflow:
git add . → stage changesgit commit -m 'msg' → save snapshotgit push → upload to GitHubgit init
git add .
git commit -m 'Initial commit'
git remote add origin https://github.com/you/repo.git
git push -u origin main
Use Case: Sharing your projects with the world.
Functions are reusable blocks of code.
Control flow: if/else, loops, switch. Functions can take parameters and return values.
fetch() makes HTTP requests. Returns a Promise.
A Promise is an object representing a future value. States: pending → fulfilled OR rejected.
.then() chains handle success. .catch() handles errors.
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));Use Case: Getting data from APIs, submitting forms to servers.
Store data in the browser that persists between sessions.
Only stores strings! Use JSON.stringify / JSON.parse for objects/arrays.
localStorage.setItem(key, value) localStorage.getItem(key) localStorage.removeItem(key)
const todos = [{ text: 'Learn JS', done: false }];
localStorage.setItem('todos', JSON.stringify(todos));
const saved = JSON.parse(localStorage.getItem('todos'));Use Case: Saving user preferences, caching data, offline-capable apps.
element.textContent — change text element.innerHTML — change HTML (⚠️ XSS risk) element.style.color = 'red' — inline styles element.classList.add/remove/toggle('class') document.createElement() + append() — safe way to add elements
title.textContent = 'New Title';
card.classList.toggle('active');
const li = document.createElement('li');
li.textContent = 'New item';
list.append(li);
Use Case: Dynamic UIs, toggling menus, updating content without reload.
if/else — conditional branching Ternary — inline conditional: condition ? ifTrue : ifFalse
Can chain: if → else if → else Nested ternaries are hard to read — prefer if/else for complex logic.
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else grade = 'C';
// Ternary
const msg = isLoggedIn ? 'Welcome!' : 'Please log in';
Use Case: Branching logic, showing different UI states.
const by default. Only use let when you need to reassign.
Never use var — it has scoping issues.
const doesn't mean immutable — objects/arrays declared with const can still be modified internally.
const name = 'Alice'; // can't reassign
let score = 0; // can reassign
score += 10;
const user = { name: 'Bob' };
user.name = 'Charlie'; // ✅ works!
Use Case: Every variable you'll ever declare.
document.querySelector(selector) — first match document.querySelectorAll(selector) — all matches (NodeList) document.getElementById(id) — by ID
Selectors use CSS syntax: .class, #id, tag
const btn = document.querySelector('.submit-btn');
const items = document.querySelectorAll('.item');
const form = document.getElementById('login-form');Use Case: Grabbing elements to modify or attach events.
Syntactic sugar over Promises. Makes async code look synchronous.
async before function — it now returns a Promise. await pauses until Promise resolves.
Always wrap in try/catch for error handling!
async function getData() {
try {
const res = await fetch(url);
if (!res.ok) throw new Error('Failed');
const data = await res.json();
return data;
} catch (err) {
console.error(err);
}
}Use Case: Clean, readable data fetching. The modern standard.
All numbers are floating-point (no separate int type).
Math.random() — random 0 to 1 Math.floor() — round down Math.ceil() — round up Math.round() — nearest integer parseInt('42') — string to integer Number('3.14') — string to number
const dice = Math.floor(Math.random() * 6) + 1;
const price = parseFloat('19.99');
const isNaN = Number.isNaN(value);
Use Case: Calculations, random generation, parsing user input.
&& (AND) — both must be true || (OR) — at least one true ! (NOT) — flips boolean
Short-circuit evaluation: value || 'default' — use default if value is falsy user && user.name — safe property access
if (isLoggedIn && isAdmin) { showDashboard(); }
const name = username || 'Anonymous';
const canEdit = isOwner && !isLocked;Use Case: Complex conditions, default values, guard clauses.
Events fire when users interact: click, submit, keydown, scroll, input.
addEventListener is the modern way (not onclick).
The event object e contains info: e.target, e.preventDefault()
btn.addEventListener('click', (e) => {
console.log('Clicked!', e.target);
});
form.addEventListener('submit', (e) => {
e.preventDefault(); // stop page reload
const data = new FormData(form);
});Use Case: Buttons, forms, keyboard shortcuts, scroll effects.
Declaration: function name() {} — hoisted Expression: const name = function() {} — not hoisted Arrow: const name = () => {} — concise, no own this
Arrow functions with one param: x => x * 2 With one line: implicit return
// Declaration
function greet(name) { return `Hello ${name}`; }
// Arrow function
const double = (n) => n * 2;
const nums = [1,2,3].map(n => n * 2); // [2,4,6]
Use Case: Breaking code into reusable pieces.
Strings hold text. Use backticks for template literals.
Template literals allow: • Variable interpolation: ${variable} • Multi-line strings • Expression evaluation: ${2 + 2}
const name = 'World';
const greeting = `Hello ${name}!`;
const multiline = `
Line 1
Line 2
`;
Use Case: Building dynamic messages, HTML templates, URLs.
Objects store related data together.
Destructuring extracts values into variables. Spread copies/merges objects.
Object.keys(), Object.values(), Object.entries() — iterate over objects.
const user = { name: 'Alice', age: 25 };
const { name, age } = user; // destructuring
const updated = { ...user, age: 26 }; // spread
Object.entries(user).forEach(([key, val]) => {
console.log(`${key}: ${val}`);
});Use Case: API responses, state management, configuration.
Classes are blueprints for creating objects.
constructor() runs when creating an instance. this refers to the current instance. Methods are functions on the class.
ES6 classes are syntactic sugar over prototypes.
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
greet() { return `Hi, I'm ${this.name}`; }
}
const alice = new User('Alice', 'alice@mail.com');Use Case: Creating reusable data structures, modeling real-world entities.
for — classic counter loop for...of — iterate over arrays/strings while — loop while condition is true
break — exit loop early continue — skip to next iteration
for (let i = 0; i < 5; i++) { console.log(i); }
const fruits = ['apple', 'banana'];
for (const fruit of fruits) { console.log(fruit); }
while (attempts < 3) { attempts++; }Use Case: Processing arrays, repeating actions, game loops.
Booleans: true or false.
Falsy values: false, 0, '', null, undefined, NaN Everything else is truthy!
'0' is truthy! [] is truthy! {} is truthy!
if ('') console.log('nope'); // won't run
if ('hello') console.log('yes'); // runs!
if (0) console.log('nope'); // won't run
if ([]) console.log('yes'); // runs! (empty array is truthy)Use Case: Conditional checks, form validation, default values.
Mutating: push(), pop(), shift(), unshift(), splice() Non-mutating: map(), filter(), reduce(), find(), includes()
map = transform each item → new array filter = keep matching items → new array reduce = combine all items → single value find = first match → single item
const doubled = [1,2,3].map(n => n * 2); // [2,4,6]
const adults = users.filter(u => u.age >= 18);
const total = prices.reduce((sum, p) => sum + p, 0);
const found = users.find(u => u.id === 5);
Use Case: Processing data, transforming arrays, calculating totals.