MASTER YOUR
CODE

// The language of the web.

JAVASCRIPT POWERS THE INTERNET.

From dynamic websites to server applications, mobile apps to AI tools, JavaScript runs everywhere. It's the only language that runs natively in browsers and has become the universal runtime for modern development.

WHY JAVASCRIPT?

JavaScript is the backbone of web development. With Node.js, it powers servers. With React, Vue, and Angular, it builds UIs. With TensorFlow.js, it runs AI in browsers. Learn once, build everywhere.

BECOME A JAVASCRIPTER.

Master variables, functions, objects, async programming, and modern ES6+ features. Join the millions of developers who make the web come alive.

BEGIN YOUR JOURNEY →

// The Path to Mastery

12 lessons. Complete JavaScript control.

LESSON 01

Introduction to JavaScript

Add interactivity to web pages

Beginner
LESSON 02

Variables & Data Types

Store values with let, const, and var

Beginner
LESSON 03

Operators & Control Flow

Compare values and make decisions

Beginner
LESSON 04

Functions

Reusable blocks of code with parameters

Beginner
LESSON 05

Arrays & Objects

Store collections of data

Intermediate
LESSON 06

DOM Manipulation

Select and modify HTML elements

Intermediate
LESSON 07

Async JavaScript

Promises, async/await, and callbacks

Intermediate
LESSON 08

ES6+ Features

Arrow functions, destructuring, modules.

Intermediate
LESSON 09

Error Handling

Try/catch and debugging techniques.

Intermediate
LESSON 10

Working with APIs

Fetch data from web services.

Advanced
LESSON 11

Browser Storage

localStorage, sessionStorage, cookies.

Advanced
LESSON 12

Modern JavaScript

NPM, Webpack, TypeScript basics.

Advanced

// Why JavaScript

JavaScript was created by Brendan Eich in 1995 in just 10 days. Originally a simple scripting language for browsers, it has evolved into the most versatile programming language in existence.

Today, JavaScript runs on every website you visit, powers servers with Node.js, builds mobile apps with React Native and Cordova, creates desktop apps with Electron, and even powers IoT devices.

The npm registry hosts over 2 million packages—the largest ecosystem of any programming language. Whatever you want to build, JavaScript has the tools.

The future of development is JavaScript. Own it.

// Tools & References

📖 MDN Docs

Mozilla Developer Network

developer.mozilla.org

📦 NPM

Node Package Manager

npmjs.com

🟨 Node.js

JavaScript Runtime

nodejs.org

📋 Can I Use

Browser Compatibility

caniuse.com

🧪 JS Bin

Online Playground

jsbin.com

⚡ V8 Engine

JavaScript Engine Docs

v8.dev

// Introduction to JavaScript

×

What is JavaScript?

JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. It was created in 1995 by Brendan Eich in just 10 days.

Why JavaScript?

  • Universal: Runs in every browser, no setup needed
  • Versatile: Frontend, backend, mobile, desktop
  • Async: Handles concurrent operations elegantly
  • Ecosystem: Millions of packages available
  • Dynamic: Interpreted, no compilation step
JAVASCRIPT'S PHILOSOPHY: "It's the only language people feel they don't need to learn before using." This accessibility makes it powerful but requires discipline.

Running JavaScript

$ node --version v20.10.0

Console Interaction

$ node Welcome to Node.js v20.10.0. > console.log("Hello, World!") Hello, World!

Your First Script

// hello.js console.log("Hello, World!"); // Run with: node hello.js

JavaScript in Browser

<script> console.log("Hello from browser!"); </script>

Quiz

1. JavaScript was created by _____ in 1995.

Hint: Netscape engineer

2. JavaScript conforms to _____ specification.

Hint: ES for short

3. Use _____ to output to console.

Hint: Print function

4. Node.js uses Google

Hint: JavaScript engine

5. In browser, JS goes in _____ tags.

Hint: HTML tag

6. JavaScript is _____ typed.

Hint: No declaration needed

7. NPM stands for Node _____ Manager.

Hint: Manages packages

8. JS runs on every _____.

Hint: Where web runs

Show Answers

Answers

  1. Brendan Eich
  2. ECMAScript
  3. console.log
  4. V8
  5. script
  6. dynamically
  7. Package
  8. browser

// Variables & Data Types

×

Variables

Variables store data values. JavaScript has three ways to declare variables.

// let - block-scoped, can be reassigned let name = "Alice"; // const - block-scoped, cannot be reassigned const PI = 3.14159; // var - function-scoped (avoid in modern JS) var oldStyle = "avoid this";

Data Types

Primitive Types

// String let name = "Python"; let single = 'quotes work'; let template = \

Quiz

1. Use _____ for constants that won

Hint: Not let or var

2. let is _____ scoped.

Hint: Scope type

3. typeof null returns _____.

Hint: JS quirk

4. parseInt converts to _____.

Hint: Whole number

5. Template literals use _____.

Hint: ` `

6. Empty string is _____ in boolean.

Hint: Falsy value

7. null represents _____ value.

Hint: On purpose

8. typeof returns a _____.

Hint: Type name

Show Answers

Answers

  1. const
  2. block
  3. object
  4. integer
  5. backticks
  6. false
  7. intentional
  8. string

// Operators & Control Flow

×

Arithmetic Operators

let a = 10; let b = 3; a + b; // 13 - Addition a - b; // 7 - Subtraction a * b; // 30 - Multiplication a / b; // 3.333... - Division a % b; // 1 - Modulus (remainder) a ** b; // 1000 - Exponentiation // Increment/Decrement a++; // a is now 11 a--; // a is now 10

Comparison Operators

  • == Equal (loose)
  • === Equal (strict)
  • != Not equal (loose)
  • !== Not equal (strict)
  • > Greater than
  • < Less than
  • >= Greater or equal
  • <= Less or equal
// Always use === and !== for strict comparison "5" == 5; // true (type coercion) "5" === 5; // false (different types)

Conditional Statements

let age = 18; if (age >= 18) { console.log("Adult"); } else if (age >= 13) { console.log("Teenager"); } else { console.log("Child"); } // Ternary operator let status = age >= 18 ? "adult" : "minor";

Logical Operators

// && - AND true && true; // true true && false; // false // || - OR true || false; // true false || false; // false // ! - NOT !true; // false

Switch Statement

let day = 1; switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; default: console.log("Other day"); }

Quiz

1. === is a _____ comparison.

Hint: No type coercion

2. % returns the _____.

Hint: Division leftover

3. Ternary uses _____ and :

Hint: Question mark

4. || returns first _____ value.

Hint: True-like

5. ! converts to _____.

Hint: True/false

6. switch needs _____ to stop.

Hint: Exit keyword

7. Loose equality is _____.

Hint: Two equals

8. ** is _____ operator.

Hint: Power

Show Answers

Answers

  1. strict
  2. remainder
  3. ?
  4. truthy
  5. boolean
  6. break
  7. ==
  8. exponentiation

// Functions

×

Function Declaration

Functions are reusable blocks of code.

// Function declaration function greet(name) { return \

Quiz

1. Arrow functions use _____ syntax.

Hint: Fat arrow

2. ...numbers is a _____ parameter.

Hint: Collects args

3. map returns a new _____.

Hint: List

4. filter keeps elements that _____.

Hint: Are true

5. reduce produces a _____ value.

Hint: One value

6. Functions can accept _____.

Hint: Functions as args

7. Default params use _____.

Hint: Assignment

8. function is a function _____.

Hint: Type

Show Answers

Answers

  1. =>
  2. rest
  3. array
  4. match
  5. single
  6. callbacks
  7. =
  8. declaration

// Arrays & Objects

×

Creating Arrays

Arrays store ordered collections of values. They're fundamental for data manipulation in JavaScript.

// Array literal (most common) const fruits = ["apple", "banana", "cherry"]; // Array constructor const numbers = new Array(1, 2, 3); // Empty array const empty = [];

Array Methods

Modern JavaScript provides powerful array methods for data transformation.

const numbers = [1, 2, 3, 4, 5]; // map - transform each element const doubled = numbers.map(x => x * 2); // [2, 4, 6, 8, 10] // filter - keep matching elements const evens = numbers.filter(x => x % 2 === 0); // [2, 4] // reduce - accumulate to single value const sum = numbers.reduce((acc, x) => acc + x, 0); // 15 // find - get first matching element const firstEven = numbers.find(x => x % 2 === 0); // 2

Destructuring Arrays

Destructuring provides a concise way to extract values from arrays.

// Basic destructuring const [first, second, third] = ["a", "b", "c"]; // Skip elements with commas const [first, , third] = [1, 2, 3]; // first=1, third=3 // Rest pattern const [head, ...tail] = [1, 2, 3, 4]; // head=1, tail=[2,3,4] // Default values const [a, b, c = "default"] = [1, 2]; // c="default"
CHAINING METHODS: Array methods can be chained together for powerful data transformations: array.filter().map().sort()

Working with Objects

Objects store key-value pairs and form the foundation of JavaScript's object-oriented capabilities.

// Object literal const person = { name: "Alice", age: 25, greet() { return `Hello, I'm ${this.name}`; } }; // Accessing properties person.name; // "Alice" (dot notation) person["age"]; // 25 (bracket notation) person.greet(); // "Hello, I'm Alice"

Destructuring Objects

const user = { name: "Bob", email: "bob@example.com", age: 30 }; // Basic destructuring const { name, email } = user; // Rename variables const { name: userName, age: userAge } = user; // Default values const { name, role = "user" } = user; // Nested destructuring const { address: { city } } = { address: { city: "NYC" } };

Spread Operator

The spread operator (...) expands arrays and objects into individual elements.

// Spread in arrays const arr1 = [1, 2]; const arr2 = [3, 4]; const combined = [...arr1, ...arr2]; // [1, 2, 3, 4] // Copy array const copy = [...arr1]; // Spread in objects const defaults = { theme: "dark", lang: "en" }; const settings = { ...defaults, theme: "light" }; // Override theme // Copy object const clone = { ...person };

Quiz

1. map() returns a new _____.

Hint: List type

2. filter() keeps elements that _____.

Hint: Pass the test

3. Destructuring uses _____ brackets for arrays.

Hint: [ ]

4. Spread operator uses _____ dots.

Hint: ...

Show Answers

Answers

  1. array
  2. match
  3. square
  4. three

// DOM Manipulation

×

Selecting Elements

The DOM (Document Object Model) represents the page structure. JavaScript can select and manipulate any element.

// By ID (returns single element) const header = document.getElementById("header"); // By class (returns HTMLCollection) const buttons = document.getElementsByClassName("btn"); // Query selector (CSS-like, first match) const firstBtn = document.querySelector(".btn"); // Query selector all (all matches) const allBtns = document.querySelectorAll(".btn");

Modifying Content

const element = document.querySelector("#myElement"); // Text content (safe, no HTML) element.textContent = "New text content"; // HTML content (parses HTML) element.innerHTML = "<strong>Bold text</strong>"; // Attributes element.setAttribute("data-id", "123"); element.getAttribute("data-id"); element.removeAttribute("title");

Modifying Styles

const box = document.querySelector(".box"); // Inline styles box.style.color = "red"; box.style.backgroundColor = "#000"; box.style.display = "none"; // CSS classes box.classList.add("active"); box.classList.remove("hidden"); box.classList.toggle("visible"); box.classList.contains("active"); // true/false
EVENT DELEGATION: Attach one event listener to a parent element and handle events from children. More efficient than adding listeners to each child.

Event Listeners

Events allow your code to respond to user interactions.

const button = document.querySelector("#myButton"); // Add event listener button.addEventListener("click", (event) => { console.log("Button clicked!"); console.log(event.target); // The clicked element }); // Common events: click, mouseover, keydown, submit, input, change // Remove event listener const handler = () => console.log("Click"); button.addEventListener("click", handler); button.removeEventListener("click", handler);

Creating Elements

// Create new element const newDiv = document.createElement("div"); newDiv.textContent = "Hello World!"; newDiv.classList.add("container"); // Add to DOM document.body.appendChild(newDiv); // Insert at specific position const container = document.querySelector("#container"); container.prepend(newDiv); // First child container.before(newDiv); // Before element container.after(newDiv); // After element

Form Handling

const form = document.querySelector("#myForm"); form.addEventListener("submit", (e) => { e.preventDefault(); // Prevent page reload // Get form data const formData = new FormData(form); const name = formData.get("name"); const email = formData.get("email"); console.log(`Name: ${name}, Email: ${email}`); }); // Input value const input = document.querySelector("#username"); console.log(input.value); // Current input value

Quiz

1. querySelector returns the _____ match.

Hint: Single element

2. addEventListener takes _____ parameters.

Hint: Event and callback

3. preventDefault stops _____ behavior.

Hint: Browser default

4. textContent is _____ than innerHTML.

Hint: No XSS risk

Show Answers

Answers

  1. first
  2. two
  3. default
  4. safer

// Async JavaScript

×

Callbacks

Callbacks are functions passed as arguments to other functions, executed after an operation completes.

function fetchData(callback) { setTimeout(() => { const data = { id: 1, name: "Alice" }; callback(null, data); }, 1000); } fetchData((err, data) => { if (err) { console.log("Error:", err); } else { console.log("Data:", data); } });
CALLBACK HELL: Nested callbacks can become difficult to read. Promises and async/await solve this problem elegantly.

Promises

Promises represent values that may not exist yet but will be resolved at some point in the future.

const promise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("Success!"); } else { reject("Failed"); } }); // Consuming promises promise .then(result => console.log(result)) // Success handler .catch(error => console.log(error)) // Error handler .finally(() => console.log("Done")); // Always runs

Async/Await

Async/await is syntactic sugar over promises, making asynchronous code look synchronous.

function fetchUser(id) { return new Promise(resolve => { setTimeout(() => { resolve({ id, name: "Alice" }); }, 1000); }); } // Async function async function getUser(id) { try { const user = await fetchUser(id); console.log(`User: ${user.name}`); return user; } catch (error) { console.log("Error:", error); } } // Call async function getUser(1);

Fetch API

The Fetch API provides a modern way to make HTTP requests.

// GET request fetch("https://api.example.com/users") .then(response => { if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.log("Error:", error)); // With async/await async function getUsers() { const response = await fetch("https://api.example.com/users"); const data = await response.json(); return data; }

Error Handling

async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error("Fetch failed:", error.message); return null; } }

Promise.all

Execute multiple promises in parallel and wait for all to complete.

const promise1 = fetch("/api/users"); const promise2 = fetch("/api/posts"); const promise3 = fetch("/api/comments"); // Wait for all promises const [users, posts, comments] = await Promise.all([ promise1, promise2, promise3 ]); // Promise.race - first to settle const fastest = await Promise.race([promise1, promise2]); // Promise.allSettled - wait for all regardless of outcome const results = await Promise.allSettled([promise1, promise2]);

Quiz

1. Promises have _____ states.

Hint: Pending, fulfilled, rejected

2. await can only be used in _____ functions.

Hint: Async keyword

3. Promise.all waits for _____ to complete.

Hint: Every promise

4. fetch returns a _____.

Hint: Async result

Show Answers

Answers

  1. three
  2. async
  3. all
  4. promise

// ES6+ Features

×

Arrow Functions

Arrow functions provide a concise syntax and lexically bind the 'this' value.

// Traditional function function add(a, b) { return a + b; } // Arrow function (full syntax) const add = (a, b) => { return a + b; }; // Arrow function (implicit return) const add = (a, b) => a + b; // Single parameter (no parentheses needed) const square = x => x * x; // No parameters const greet = () => "Hello!";
THIS BINDING: Arrow functions don't have their own 'this'. They inherit 'this' from the enclosing scope, which is useful for callbacks inside methods.

Template Literals

Template literals allow embedded expressions and multi-line strings using backticks.

const name = "Alice"; const age = 25; // String interpolation const greeting = `Hello, ${name}! You are ${age} years old.`; // Multi-line strings const html = ` <div class="container"> <h1>${name}</h1> <p>Age: ${age}</p> </div> `; // Expression evaluation const result = `Sum: ${2 + 2}`; // "Sum: 4"

let and const

ES6 introduced block-scoped variable declarations, replacing the function-scoped 'var'.

// const - for values that won't be reassigned const API_URL = "https://api.example.com"; const MAX_SIZE = 100; // let - for values that will change let count = 0; count = count + 1; // Block scope if (true) { let blockScoped = "inside"; console.log(blockScoped); // Works } // console.log(blockScoped); // Error! Not accessible

Modules

ES modules allow you to split code into separate files for better organization.

// math.js - Export export const add = (a, b) => a + b; export const subtract = (a, b) => a - b; const multiply = (a, b) => a * b; export default multiply; // main.js - Import import multiply, { add, subtract } from "./math.js"; add(2, 3); // 5 multiply(2, 3); // 6 (default export) // Import all as namespace import * as math from "./math.js"; math.add(2, 3);

Classes

ES6 classes provide syntactic sugar over JavaScript's prototype-based inheritance.

class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { return `Hi, I'm ${this.name}`; } static isAdult(age) { return age >= 18; } } // Inheritance class Student extends Person { constructor(name, age, grade) { super(name, age); this.grade = grade; } study() { return `${this.name} is studying`; } }

Quiz

1. Arrow functions use _____ syntax.

Hint: Fat arrow

2. Template literals use _____ quotes.

Hint: ` `

3. const cannot be _____.

Hint: Changed

4. super() calls the _____ constructor.

Hint: Base class

Show Answers

Answers

  1. =>
  2. backtick
  3. reassigned
  4. parent

// Error Handling

×

Try/Catch

Try/catch blocks allow you to handle errors gracefully without crashing your application.

try { // Code that might throw an error const result = JSON.parse("invalid json"); console.log(result); } catch (error) { // Handle the error console.log("Error:", error.message); console.log("Type:", error.name); } console.log("Program continues..."); // Still runs

Finally Block

The finally block always executes, whether an error occurred or not.

try { console.log("Trying..."); throw new Error("Something went wrong"); } catch (error) { console.log("Caught:", error.message); } finally { console.log("Cleanup code always runs"); }

Throwing Errors

You can throw custom errors to handle exceptional conditions in your code.

function divide(a, b) { if (b === 0) { throw new Error("Cannot divide by zero"); } if (typeof a !== "number" || typeof b !== "number") { throw new TypeError("Arguments must be numbers"); } return a / b; } try { divide(10, 0); } catch (error) { console.log(`Error: ${error.name}: ${error.message}`); }
ERROR TYPES: Use specific error types (TypeError, RangeError, etc.) to make debugging easier. Custom error classes can extend Error for domain-specific errors.

Error Types

// Common built-in error types // Error - generic error new Error("Something went wrong"); // TypeError - wrong type new TypeError("Expected string, got number"); // ReferenceError - undefined variable new ReferenceError("Variable not defined"); // SyntaxError - invalid code new SyntaxError("Unexpected token"); // RangeError - value out of range new RangeError("Number out of range");

Debugging with Console

// Different console methods for debugging console.log("General output"); // Standard logging console.info("Information"); // Info message console.warn("Warning!"); // Warning message console.error("Error occurred"); // Error message // Grouped logging console.group("User Details"); console.log("Name: Alice"); console.log("Age: 25"); console.groupEnd(); // Table display console.table([{ name: "Alice", age: 25 }]); // Stack trace console.trace("Trace message");

Stack Traces

Stack traces show the sequence of function calls that led to an error.

function a() { b(); } function b() { c(); } function c() { throw new Error("Error in function c"); } try { a(); } catch (error) { console.log("Stack trace:"); console.log(error.stack); // Shows: c -> b -> a }

Quiz

1. try block contains _____ code.

Hint: May throw errors

2. finally runs _____.

Hint: Every time

3. TypeError is for wrong _____.

Hint: Data type

4. error.stack shows the _____.

Hint: Call sequence

Show Answers

Answers

  1. risky
  2. always
  3. type
  4. trace

// Working with APIs

×

REST API Basics

REST (Representational State Transfer) APIs use HTTP methods to perform CRUD operations on resources.

// HTTP Methods for REST APIs GET /users // Read all users GET /users/1 // Read user with id 1 POST /users // Create new user PUT /users/1 // Update user 1 (full) PATCH /users/1 // Partial update user 1 DELETE /users/1 // Delete user 1 // HTTP Status Codes 200 OK // Success 201 Created // Resource created 400 Bad Request // Invalid input 401 Unauthorized // Not authenticated 404 Not Found // Resource doesn't exist 500 Server Error // Internal error

JSON Parsing

JSON (JavaScript Object Notation) is the standard data format for APIs.

// Convert object to JSON string const user = { name: "Alice", age: 25 }; const jsonString = JSON.stringify(user); // {"name":"Alice","age":25} // Parse JSON string to object const parsed = JSON.parse(jsonString); console.log(parsed.name); // "Alice" // Pretty print JSON JSON.stringify(user, null, 2); // Formatted with indentation
API BEST PRACTICES: Always validate API responses, handle network errors, implement proper error handling, and respect rate limits. Use try/catch with async/await for cleaner error handling.

Fetch API

// GET request async function getUsers() { const response = await fetch("https://api.example.com/users"); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } const data = await response.json(); return data; } // POST request with body async function createUser(userData) { const response = await fetch("https://api.example.com/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(userData) }); return response.json(); }

Axios Library

Axios is a popular HTTP client with a cleaner API than fetch.

// Install: npm install axios import axios from "axios"; // GET request const response = await axios.get("/api/users"); console.log(response.data); // POST request await axios.post("/api/users", { name: "Alice", email: "alice@example.com" }); // Axios automatically: // - Parses JSON // - Throws on error status // - Handles request/response interceptors

Authentication

// Bearer Token (JWT) fetch("/api/protected", { headers: { "Authorization": `Bearer ${token}` } }); // API Key fetch(`/api/data?api_key=${API_KEY}`); // Basic Auth (Base64 encoded) const credentials = btoa(`username:password`); fetch("/api/private", { headers: { "Authorization": `Basic ${credentials}` } });

Handling Responses

async function handleApiCall() { try { const response = await fetch("/api/data"); switch (response.status) { case 200: return await response.json(); case 401: throw new Error("Authentication required"); case 404: throw new Error("Resource not found"); default: throw new Error(`Server error: ${response.status}`); } } catch (error) { console.error("API Error:", error.message); return null; } }

Quiz

1. POST is used to _____ data.

Hint: Add new

2. JSON.stringify converts to _____.

Hint: Text format

3. 404 status means _____.

Hint: Missing resource

4. JWT stands for JSON Web _____.

Hint: Auth token

Show Answers

Answers

  1. create
  2. string
  3. not found
  4. token

// Browser Storage

×

LocalStorage

LocalStorage stores data persistently with no expiration time. Data survives browser restarts.

// Store data localStorage.setItem("username", "Alice"); localStorage.setItem("theme", "dark"); // Retrieve data const username = localStorage.getItem("username"); console.log(username); // "Alice" // Remove item localStorage.removeItem("theme"); // Clear all localStorage.clear(); // Storage limit: ~5-10MB per origin

SessionStorage

SessionStorage is similar to LocalStorage but data is cleared when the page session ends.

// Same API as localStorage sessionStorage.setItem("tempData", "123"); sessionStorage.getItem("tempData"); // Data persists through page reloads // Data is cleared when tab/window closes // Useful for: // - Form data during session // - Multi-step wizard state // - Shopping cart before checkout
STORAGE LIMITATIONS: Both LocalStorage and SessionStorage only store strings. Objects must be serialized with JSON.stringify(). Storage is synchronous and blocking - large operations can affect performance.

Storing Objects

// Store object (must stringify) const user = { name: "Alice", age: 25 }; localStorage.setItem("user", JSON.stringify(user)); // Retrieve and parse const storedUser = JSON.parse(localStorage.getItem("user")); console.log(storedUser.name); // "Alice" // Helper functions function saveToStorage(key, value) { localStorage.setItem(key, JSON.stringify(value)); } function getFromStorage(key) { const item = localStorage.getItem(key); return item ? JSON.parse(item) : null; }

Cookies

Cookies are small pieces of data stored by the browser, automatically sent with HTTP requests.

// Set cookie (expires in 7 days) const expires = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); document.cookie = `username=Alice; expires=${expires.toUTCString()}; path=/`; // Read cookies console.log(document.cookie); // Cookie attributes HttpOnly // Not accessible via JavaScript Secure // Only sent over HTTPS SameSite // CSRF protection // Limit: ~4KB per cookie, ~20 per domain

IndexedDB

IndexedDB is a low-level API for client-side storage of structured data including files/blobs.

// Open database const request = indexedDB.open("MyDatabase", 1); request.onupgradeneeded = (event) => { const db = event.target.result; const store = db.createObjectStore("users", { keyPath: "id" }); store.createIndex("name", "name", { unique: false }); }; request.onsuccess = (event) => { const db = event.target.result; // Use database };

Storage Comparison

// When to use each: LocalStorage // Persistent user preferences SessionStorage // Temporary session data Cookies // Server-side auth/session IndexedDB // Large structured data Cache API // Offline app assets // Storage limits (approximate): LocalStorage // 5-10 MB SessionStorage // 5-10 MB Cookies // 4 KB per cookie IndexedDB // 50+ MB (varies by browser)

Quiz

1. LocalStorage stores only _____.

Hint: Text data

2. SessionStorage clears on _____.

Hint: Tab close

3. Cookies are sent with _____ requests.

Hint: Network

4. IndexedDB is for _____ data.

Hint: Complex objects

Show Answers

Answers

  1. strings
  2. close
  3. http
  4. structured

// Modern JavaScript

×

NPM (Node Package Manager)

NPM is the world's largest software registry, hosting over 2 million packages.

// Initialize a new project $ npm init -y // Install a package $ npm install express // Install as dev dependency $ npm install --save-dev nodemon // Install globally $ npm install -g typescript // Run scripts from package.json $ npm run build $ npm start $ npm test

Build Tools: Webpack & Vite

Build tools bundle, optimize, and transform your code for production.

// Webpack - powerful, configurable $ npm install --save-dev webpack webpack-cli // webpack.config.js module.exports = { entry: "./src/index.js", output: { filename: "bundle.js", path: __dirname + "/dist" }, mode: "production" }; // Vite - fast, modern, zero-config $ npm create vite@latest my-app $ cd my-app && npm install && npm run dev
VITE ADVANTAGES: Vite uses native ES modules in development for instant server start, and Rollup for optimized production builds. It's significantly faster than Webpack for development.

Babel Transpiler

Babel converts modern JavaScript (ES6+) into backward-compatible versions for older browsers.

// Install Babel $ npm install --save-dev @babel/core @babel/cli @babel/preset-env // .babelrc configuration { "presets": ["@babel/preset-env"] } // Transpile code $ npx babel src --out-dir lib // Before (ES6) const greet = (name) => `Hello ${name}`; // After (ES5) var greet = function greet(name) { return "Hello " + name; };

TypeScript Basics

TypeScript adds static typing to JavaScript, catching errors at compile time.

// Install TypeScript $ npm install -g typescript // Basic types let name: string = "Alice"; let age: number = 25; let isActive: boolean = true; // Function types function greet(name: string): string { return `Hello, ${name}`; } // Interface interface User { id: number; name: string; email?: string; // Optional } const user: User = { id: 1, name: "Alice" };

JavaScript Frameworks Overview

// React - Component-based UI function App() { const [count, setCount] = useState(0); return <button onClick={() => setCount(c + 1)}>{count}</button>; } // Vue - Progressive framework export default { data() { return { count: 0 }; } } // Angular - Full-featured framework @Component({ selector: "app-root", template: `<h1>{{title}}</h1>` }) export class AppComponent { title = "My App"; } // Svelte - Compile-time framework <script> let count = 0; </script> <button on:click={() => count++}>{count}</button>

Modern Development Workflow

// Typical modern JS project setup $ npm create vite@latest my-app -- --template react $ cd my-app // Project structure my-app/ src/ components/ // Reusable components pages/ // Page components hooks/ // Custom React hooks utils/ // Helper functions App.jsx main.jsx public/ // Static assets package.json vite.config.js // Development commands $ npm run dev // Start dev server $ npm run build // Production build $ npm run lint // Check code style $ npm run test // Run tests

Quiz

1. NPM manages _____.

Hint: Dependencies

2. Vite is a _____ tool.

Hint: Bundle code

3. TypeScript adds _____ typing.

Hint: Compile-time checks

4. Babel is a _____.

Hint: Code converter

Show Answers

Answers

  1. packages
  2. build
  3. static
  4. transpiler