- 1JavaScript in Web Development
- 2HTML + CSS + JS Working Together
- 3What JavaScript Does on the Web
- 4Adding JavaScript to a Webpage
- 5The DOM — JavaScript's Window into the Page
- 6Events — Making Pages Interactive
- 7Frontend Web Development
- 8Backend Web Development with Node.js
- 9Full-stack JavaScript
- 10Build Tools & Package Managers
- 11Real-world JavaScript in Action
- 12JavaScript Career Paths
- 13Test Your Knowledge
- 14Tips for Getting Started
JavaScript in Web Development
JavaScript in Web Development
HTML — Structure
HyperText Markup Language. Defines what's on the page — headings, paragraphs, images, links, forms, buttons.
CSS — Style
Cascading Style Sheets. Defines how things look — colors, fonts, layouts, animations, responsive design.
JavaScript — Behaviour
Defines what things do — responds to clicks, loads data, updates the page, validates forms, powers apps.
The Perfect Analogy
Think of a website like a human body:
- HTML is the skeleton — the structure and bones
- CSS is the skin and clothes — how it looks
- JavaScript is the muscles and brain — what it can do and how it responds
HTML + CSS + JS Working Together
HTML + CSS + JS Working Together
1<!DOCTYPE html>2<html>3<head>4 <!-- CSS: defines how things look -->5 <style>6 body { font-family: sans-serif; background: #0f172a; color: white; display: flex; flex-direction: column; align-items: center; padding: 30px; gap: 16px; }7 .card { background: #1e293b; border-radius: 12px; padding: 24px; width: 280px; text-align: center; transition: transform 0.3s, box-shadow 0.3s; }8 .card:hover { transform: translateY(-4px); box-shadow: 0 10px 30px rgba(99,102,241,0.3); }9 h2 { margin: 0 0 8px; font-size: 20px; }10 p { margin: 0; color: #94a3b8; font-size: 14px; }11 button { padding: 12px 28px; background: #6366f1; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 15px; font-weight: bold; transition: background 0.2s; }12 button:hover { background: #4f46e5; }13 #counter { font-size: 48px; font-weight: bold; color: #4ade80; }14 #message { font-size: 14px; color: #94a3b8; }15 </style>16</head>17<body>18 <!-- HTML: defines structure -->19 <div class="card">20 <h2>⚡ JS Counter</h2>21 <p>HTML gives structure, CSS gives style</p>22 <div id="counter">0</div>23 <div id="message">Click to start!</div>24 </div>25 <button onclick="increment()">Click Me!</button>26 <button onclick="reset()" style="background:#475569">Reset</button>2728 <!-- JavaScript: defines behaviour -->29 <script>30 let count = 0;31 const milestones = { 5: '🎉 5 clicks!', 10: '🔥 10 clicks!', 25: '🚀 25 — legend!', 50: '👑 50 — champion!' };3233 function increment() {34 count++;35 document.getElementById('counter').textContent = count;36 // JS modifies CSS dynamically37 const hue = (count * 15) % 360;38 document.getElementById('counter').style.color = `hsl(${hue}, 80%, 65%)`;39 document.getElementById('message').textContent = milestones[count] || `${count} click${count > 1 ? 's' : ''}`;40 }4142 function reset() {43 count = 0;44 document.getElementById('counter').textContent = '0';45 document.getElementById('counter').style.color = '#4ade80';46 document.getElementById('message').textContent = 'Click to start!';47 }48 </script>49</body>50</html>
What JavaScript Does on the Web
What JavaScript Does on the Web
| Without JavaScript | With JavaScript |
|---|---|
| Clicking a menu item reloads the whole page | Dropdown opens instantly — no reload |
| Form submitted → full page refresh | Form validates and submits in the background |
| Seeing new tweets requires refreshing | New tweets appear automatically as you scroll |
| Product search requires a new page load | Results filter instantly as you type |
| Shopping cart requires a dedicated cart page | Cart updates live in a corner badge |
| Image gallery is a separate page | Lightbox opens inline — no navigation |
| Chat requires refreshing to see new messages | Messages appear in real time |
| Maps are static images | Maps pan, zoom, and load tiles dynamically |
Dynamic Page Updates
Change content without reloading — update a price, show a notification, swap an image. No round-trip to the server.
Form Validation
Check email format, password strength, and required fields instantly — before the user even submits.
Fetching Live Data
Load weather, stock prices, social feeds, search results, and notifications without refreshing the page.
Animations & Transitions
Smooth scrolling, parallax effects, page transitions, micro-interactions that make the UI feel alive.
Interactive Maps
Google Maps, Mapbox, Leaflet — all powered by JavaScript rendering tiles and responding to gestures.
SPAs — Single Page Apps
Gmail, Twitter, Notion — entire apps that navigate without ever reloading the page.
Adding JavaScript to a Webpage
Adding JavaScript to a Webpage
1. Inline — inside an HTML attribute
Write JS directly in an HTML event attribute like onclick. Avoid this — it mixes logic with markup and is hard to maintain.
1<!-- ❌ Avoid — hard to maintain, no separation of concerns -->2<button onclick="alert('Hello!')">Click me</button>3<input onchange="console.log(this.value)" />
2. Internal — inside a <script> tag
Write JS inside a <script> block in your HTML file. Fine for small demos. Always place at the bottom of <body> so HTML loads first.
1<!DOCTYPE html>2<html>3<body>4 <h1 id="title">Hello</h1>56 <!-- ✅ Script at the bottom — HTML is ready when JS runs -->7 <script>8 document.getElementById('title').textContent = 'Hello, JavaScript!';9 console.log('Page loaded!');10 </script>11</body>12</html>
3. External — a separate .js file (recommended)
Keep JavaScript in a .js file and link it with <script src="...">. Add defer so the script runs after HTML is parsed. This is the standard for all real projects.
1<!-- index.html -->2<!DOCTYPE html>3<html>4<head>5 <!-- defer = download in background, run after HTML is ready -->6 <script src="app.js" defer></script>7</head>8<body>9 <h1 id="title">Hello</h1>10 <button id="btn">Click me</button>11</body>12</html>1314// app.js — lives in a separate file15document.getElementById('btn').addEventListener('click', () => {16 document.getElementById('title').textContent = 'You clicked!';17});
defer vs async
Two attributes control when external scripts load and run:
defer— Script downloads in parallel, runs after HTML is fully parsed. Scripts run in order. Best for most cases.async— Script downloads in parallel, runs immediately when ready (may be before HTML finishes). Order not guaranteed. Best for independent scripts like analytics.- No attribute — HTML parsing pauses until the script downloads and runs. Slowest — avoid.
The DOM — JavaScript's Window into the Page
The DOM — JavaScript's Window into the Page
What is the DOM?
The DOM is a live, in-memory tree representation of your HTML. Every tag becomes a node. JavaScript can:
- Select any element:
document.querySelector('#title') - Read content:
element.textContent - Change content:
element.textContent = 'New text' - Change styles:
element.style.color = 'red' - Add/remove classes:
element.classList.add('active') - Create new elements:
document.createElement('div') - Remove elements:
element.remove() - Listen for events:
element.addEventListener('click', fn)
1// Selecting elements2const title = document.querySelector('h1'); // first h13const allLinks = document.querySelectorAll('a'); // all links4const byId = document.getElementById('main'); // by ID5const byClass = document.querySelector('.hero'); // by class67// Reading content8console.log(document.title); // Page title from <title> tag9console.log(document.body.children.length); // Number of direct body children1011// Changing content12document.querySelector('body').style.background = '#1e293b';13document.querySelector('body').style.color = '#f1f5f9';14console.log('Page background changed by JavaScript!');1516// Creating and adding elements17const newDiv = document.createElement('div');18newDiv.textContent = '✅ This element was created by JavaScript!';19newDiv.style.cssText = 'background:#16a34a;color:white;padding:12px;border-radius:8px;margin:10px 0;font-family:sans-serif';20document.body.appendChild(newDiv);2122// Working with classes23newDiv.classList.add('highlight');24newDiv.classList.remove('highlight');25console.log('Element created and added to DOM!');
Events — Making Pages Interactive
Events — Making Pages Interactive
| Event | Fires When | Example Use |
|---|---|---|
| click | Element is clicked | Button action, toggle menu, like button |
| input | Value of input changes | Live search, character count, preview |
| submit | Form is submitted | Validate and send form data |
| keydown / keyup | Key is pressed / released | Keyboard shortcuts, game controls |
| mouseover / mouseout | Mouse enters / leaves element | Tooltip, hover card, highlight |
| scroll | Page or element is scrolled | Sticky header, lazy load, progress bar |
| resize | Browser window resizes | Responsive adjustments, redraw canvas |
| load | Page / resource fully loaded | Init animations, start timers |
| DOMContentLoaded | HTML parsed (before images load) | Safe to query DOM elements |
| focus / blur | Input gains / loses focus | Show/hide helper text, validate on leave |
| change | Select, checkbox, radio changes | Filter products, toggle settings |
| contextmenu | Right-click on element | Custom context menu |
1<!DOCTYPE html>2<html>3<head>4 <style>5 body { font-family: sans-serif; background: #0f172a; color: white; padding: 20px; }6 input { width: 100%; padding: 10px; border-radius: 8px; border: 2px solid #334155; background: #1e293b; color: white; font-size: 15px; margin: 8px 0; outline: none; box-sizing: border-box; }7 input:focus { border-color: #6366f1; }8 .box { background: #1e293b; border-radius: 10px; padding: 16px; margin: 10px 0; }9 #hover-box { background: #1e3a5f; padding: 20px; border-radius: 10px; text-align: center; cursor: pointer; transition: background 0.3s; user-select: none; }10 #log { max-height: 100px; overflow-y: auto; background: #0f172a; padding: 10px; border-radius: 8px; font-size: 12px; font-family: monospace; color: #4ade80; }11 </style>12</head>13<body>14 <div class="box">15 <b>⌨️ Input event — live character count</b>16 <input id="txt" placeholder="Type something..." maxlength="50">17 <div id="count" style="color:#94a3b8;font-size:13px">0 / 50 characters</div>18 </div>1920 <div id="hover-box">🖱️ Hover over me!</div>2122 <div class="box">23 <b>📋 Event Log</b>24 <div id="log">Waiting for events...</div>25 </div>2627 <script>28 function log(msg) {29 const el = document.getElementById('log');30 el.innerHTML = `${new Date().toLocaleTimeString()} → ${msg}<br>` + el.innerHTML;31 }3233 // input event34 document.getElementById('txt').addEventListener('input', (e) => {35 const len = e.target.value.length;36 document.getElementById('count').textContent = `${len} / 50 characters`;37 log(`input: "${e.target.value}"`);38 });3940 // focus / blur events41 document.getElementById('txt').addEventListener('focus', () => log('focus — input gained focus'));42 document.getElementById('txt').addEventListener('blur', () => log('blur — input lost focus'));4344 // mouseover / mouseout45 const box = document.getElementById('hover-box');46 box.addEventListener('mouseover', () => { box.style.background='#1d4ed8'; log('mouseover'); });47 box.addEventListener('mouseout', () => { box.style.background='#1e3a5f'; log('mouseout'); });48 box.addEventListener('click', () => log('click!'));4950 // scroll event51 window.addEventListener('scroll', () => log('scroll'));52 </script>53</body>54</html>
Frontend Web Development
Frontend Web Development
Vanilla JavaScript
Plain JavaScript — no frameworks. You use the browser's built-in APIs directly: document.querySelector, addEventListener, fetch. Best for learning fundamentals and small interactive features.
1// Vanilla JS — no framework needed2document.querySelector('#btn').addEventListener('click', async () => {3 const res = await fetch('https://api.github.com/users/torvalds');4 const user = await res.json();5 document.querySelector('#name').textContent = user.name;6 document.querySelector('#bio').textContent = user.bio;7});
Component-based Frameworks
React, Vue, and Svelte let you break your UI into reusable components — self-contained pieces of HTML, CSS, and JS. A <Button>, <Card>, or <Modal> becomes a reusable building block.
1// React component — JavaScript that returns HTML (JSX)2function ProductCard({ name, price, inStock }) {3 return (4 <div className="card">5 <h3>{name}</h3>6 <p>${price.toFixed(2)}</p>7 <span className={inStock ? 'green' : 'red'}>8 {inStock ? 'In Stock' : 'Out of Stock'}9 </span>10 <button disabled={!inStock}>Add to Cart</button>11 </div>12 );13}1415// Used like an HTML tag:16<ProductCard name="MacBook Pro" price={1999} inStock={true} />
State Management
As apps grow, managing state (the data that drives the UI) becomes critical. When a user adds an item to a cart, updates a profile, or toggles a setting — that's state changing. Tools like React's useState, Redux, Zustand, and Pinia handle state.
1// React — useState hook2import { useState } from 'react';34function LikeButton() {5 const [liked, setLiked] = useState(false);6 const [count, setCount] = useState(42);78 const toggle = () => {9 setLiked(!liked);10 setCount(liked ? count - 1 : count + 1);11 };1213 return (14 <button onClick={toggle} style={{ color: liked ? 'red' : 'gray' }}>15 {liked ? '❤️' : '🤍'} {count}16 </button>17 );18}
Routing — Multiple Pages in an SPA
Single Page Applications use client-side routing to navigate between 'pages' without reloading. React Router, Vue Router, and TanStack Router intercept link clicks and swap components instead of fetching new HTML from the server.
1// React Router — client-side navigation2import { Routes, Route, Link } from 'react-router-dom';34function App() {5 return (6 <div>7 <nav>8 <Link to="/">Home</Link>9 <Link to="/products">Products</Link>10 <Link to="/about">About</Link>11 </nav>12 {/* Components swap — no page reload */}13 <Routes>14 <Route path="/" element={<Home />} />15 <Route path="/products" element={<Products />} />16 <Route path="/about" element={<About />} />17 </Routes>18 </div>19 );20}
Backend Web Development with Node.js
Backend Web Development with Node.js
Building a REST API with Express
Express is the most popular Node.js web framework. It lets you define routes that respond to HTTP requests — the backbone of every modern web API.
1const express = require('express');2const app = express();3app.use(express.json());45// In-memory data (real app would use a database)6let products = [7 { id: 1, name: 'Laptop', price: 999 },8 { id: 2, name: 'Monitor', price: 349 },9];1011// GET all products12app.get('/api/products', (req, res) => {13 res.json(products);14});1516// GET one product17app.get('/api/products/:id', (req, res) => {18 const product = products.find(p => p.id === Number(req.params.id));19 if (!product) return res.status(404).json({ error: 'Not found' });20 res.json(product);21});2223// POST — create a new product24app.post('/api/products', (req, res) => {25 const newProduct = { id: Date.now(), ...req.body };26 products.push(newProduct);27 res.status(201).json(newProduct);28});2930app.listen(3000, () => console.log('API running on port 3000'));
Connecting to a Database
Node.js can connect to any database — SQL (PostgreSQL, MySQL) or NoSQL (MongoDB, Redis). ORM libraries like Prisma and Drizzle make database queries type-safe and clean.
1// Prisma ORM — type-safe database access2import { PrismaClient } from '@prisma/client';3const prisma = new PrismaClient();45// GET all users from PostgreSQL6app.get('/api/users', async (req, res) => {7 const users = await prisma.user.findMany({8 where: { active: true },9 select: { id: true, name: true, email: true }, // never return passwords!10 orderBy: { createdAt: 'desc' },11 });12 res.json(users);13});1415// POST — create a user16app.post('/api/users', async (req, res) => {17 const { name, email, password } = req.body;18 const hash = await bcrypt.hash(password, 12); // always hash!19 const user = await prisma.user.create({20 data: { name, email, passwordHash: hash },21 });22 res.status(201).json({ id: user.id, name: user.name });23});
Authentication with JWT
User authentication is a key backend task. JWT (JSON Web Tokens) are a popular way to identify logged-in users — the server signs a token, the client stores it and sends it with every request.
1const jwt = require('jsonwebtoken');2const SECRET = process.env.JWT_SECRET; // stored in .env — never in code!34// Login endpoint5app.post('/api/login', async (req, res) => {6 const { email, password } = req.body;78 // Find user and verify password9 const user = await prisma.user.findUnique({ where: { email } });10 if (!user) return res.status(401).json({ error: 'Invalid credentials' });1112 const valid = await bcrypt.compare(password, user.passwordHash);13 if (!valid) return res.status(401).json({ error: 'Invalid credentials' });1415 // Issue token — expires in 7 days16 const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: '7d' });17 res.json({ token });18});1920// Protected route — middleware checks token21function requireAuth(req, res, next) {22 const token = req.headers.authorization?.split(' ')[1];23 if (!token) return res.status(401).json({ error: 'Not logged in' });24 try {25 req.user = jwt.verify(token, SECRET);26 next();27 } catch {28 res.status(401).json({ error: 'Invalid token' });29 }30}3132app.get('/api/profile', requireAuth, async (req, res) => {33 const user = await prisma.user.findUnique({ where: { id: req.user.userId } });34 res.json(user);35});
Full-stack JavaScript
Full-stack JavaScript
The JavaScript Advantage
Every other language requires learning JavaScript anyway — you need it for the browser. But with Node.js, you can use JavaScript for the server too. One language, one ecosystem, one team — this is why JavaScript dominates full-stack web development.
| Stack | Frontend | Backend | Database |
|---|---|---|---|
| MERN | React | Node.js + Express | MongoDB |
| MEAN | Angular | Node.js + Express | MongoDB |
| MEVN | Vue | Node.js + Express | MongoDB |
| T3 Stack | React + Next.js | Next.js API Routes | PostgreSQL (Prisma) |
| JAMstack | React / Vue / Svelte | Serverless Functions | Headless CMS / APIs |
1// Next.js — client and server code in the same project23// ━━━ SERVER SIDE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━4// app/api/posts/route.ts — runs on the server (Node.js)5export async function GET() {6 // Direct DB access — this code NEVER reaches the browser7 const posts = await prisma.post.findMany({ take: 10 });8 return Response.json(posts);9}1011export async function POST(request: Request) {12 const body = await request.json();13 const post = await prisma.post.create({ data: body });14 return Response.json(post, { status: 201 });15}1617// ━━━ CLIENT SIDE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━18// app/posts/page.tsx — this component renders in the browser19'use client';20import { useState, useEffect } from 'react';2122export default function PostsPage() {23 const [posts, setPosts] = useState([]);2425 useEffect(() => {26 // Browser JS calling the server API above27 fetch('/api/posts').then(r => r.json()).then(setPosts);28 }, []);2930 return (31 <ul>32 {posts.map(post => (33 <li key={post.id}>{post.title}</li>34 ))}35 </ul>36 );37}
Build Tools & Package Managers
Build Tools & Package Managers
The Modern JS Toolchain
Real-world JavaScript in Action
Real-world JavaScript in Action
| Product | Frontend | Backend | What JS Does |
|---|---|---|---|
| Vanilla JS + internal frameworks | Node.js for some services | Search suggestions, Maps, Gmail real-time updates | |
| Facebook / Meta | React (they created it) | Node.js + others | News feed, reactions, Messenger real-time chat |
| Netflix | React | Node.js (API gateway) | Streaming UI, personalised recommendations display |
| Airbnb | React | Node.js | Search filters, map interaction, booking flow |
| GitHub | React + Vanilla JS | Node.js | Code editor, pull request diffs, notifications |
| Slack | React + Electron | Node.js | Real-time messaging, notifications, file uploads |
| VS Code | TypeScript + Electron | Node.js (extensions) | The entire editor — VS Code is a web app wrapped in Electron |
| Notion | React | Node.js | Block editor, real-time collaboration, syncing |
VS Code is JavaScript
VS Code — the most popular code editor in the world — is built with TypeScript (a superset of JavaScript) and runs on Electron, which is a Chromium browser window running a Node.js app. You're writing JavaScript inside an application built with JavaScript.
JavaScript Career Paths
JavaScript Career Paths in Web Development
Frontend Developer
Builds UIs with React / Vue / Angular. Focuses on CSS, accessibility, performance, and user experience. High demand role.
Backend Developer
Builds APIs and services with Node.js + Express / NestJS. Manages databases, auth, and server infrastructure.
Full-stack Developer
Works across the entire stack. Uses Next.js or similar to handle both frontend and backend in one project.
React Native Developer
Builds cross-platform iOS and Android apps using JavaScript and React Native — reusing web skills for mobile.
| Role | Key Technologies | Typical Starting Skills |
|---|---|---|
| Frontend Developer | React, TypeScript, CSS, Tailwind, Vite | HTML, CSS, JS fundamentals, React basics |
| Backend Developer | Node.js, Express/Fastify, SQL/NoSQL, REST/GraphQL | JS, Node, databases, HTTP, auth |
| Full-stack Developer | Next.js, React, Node, Prisma, TypeScript | All of the above at a shallower depth |
| React Native Developer | React Native, Expo, TypeScript | React, JS, some mobile concepts |
| DevOps / Platform (JS) | Node.js, Docker, CI/CD, AWS/Vercel | Backend + infrastructure knowledge |
Test Your Knowledge
Test Your Knowledge
What are the three core technologies of the web, and what is JavaScript's specific role?
What is the recommended way to include JavaScript in a production HTML page?
What is the DOM?
What does npm stand for and what is it used for?
What is the main advantage of full-stack JavaScript development?
Tips for Getting Started
Tips for Getting Started in Web Development
- 1Learn HTML and CSS basics before diving deep into JavaScript — understanding the structure you'll be manipulating makes everything click faster.
- 2Master vanilla JavaScript (DOM, events, fetch) before picking a framework. React and Vue will make much more sense once you know what they're abstracting.
- 3Build small projects as early as possible — a to-do list, a weather app, a quiz game. Building teaches what reading tutorials cannot.
- 4Use the browser DevTools constantly — the Console, Elements tab, Network tab, and Sources tab are your primary development tools.
- 5Don't try to learn every framework at once. Pick one (React is the most in-demand), go deep with it, and learn others later.
- 6TypeScript is worth learning early. Most job listings expect it, and it catches real bugs. Start adding types to your JS as soon as you're comfortable with the basics.
- 7The npm ecosystem is vast — don't reinvent the wheel. Search npm for existing solutions before building from scratch.
- 8VS Code + the ESLint and Prettier extensions will make you a faster, more consistent developer from day one.
Variables & Data Types
The foundation — learn how to store and work with data in JavaScript.
Control Flow
if/else, loops, switch — how to make decisions and repeat actions in code.
Functions
The building blocks of every JavaScript program — how to write reusable code.
DOM Manipulation
Put your JavaScript to work — select elements, handle events, and update the page.
You're ready to build the web!
JavaScript is the language of the web — client, server, mobile, and desktop. Every skill you learn in JavaScript compounds across the entire development stack. Start with the fundamentals, build small projects, and the rest will follow.
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.