Master JavaScript
From Scratch
The only JavaScript guide you'll ever need. Crystal-clear explanations, live playground, and everything a beginner needs to go from zero to confident.
JavaScript is a programming language that runs in web browsers (and servers). It's what makes websites interactive β buttons that respond, forms that validate, animations that play, and apps that update without reloading the page.
Think of a website like a person:
The skeleton β structure & content
The clothes β design & style
The brain β logic & interaction
Where does JS run?
| Environment | Tool | Use Case |
|---|---|---|
| Browser | Chrome, Firefox, Safari | Websites, Web Apps |
| Server | Node.js | APIs, Backend Logic |
| Mobile | React Native | iOS & Android Apps |
| Desktop | Electron | VS Code, Slack, etc. |
π Runs Everywhere
Every device with a browser already has JavaScript installed. No setup, no downloads β just open browser and write code.
π¦ One Language, Full Stack
With JS you can build the frontend (what users see) AND the backend (server logic). One language rules them all.
π Most Popular Language
JavaScript has been the #1 most-used language on GitHub for 10+ years in a row. Biggest community, most jobs.
β‘ Instant Feedback
Unlike Python or Java, you see results instantly in the browser. Perfect for learning β write code, see magic happen immediately.
A variable is a named container that holds a value. Imagine it as a labeled box β you give it a name, put something inside, and can use it later.
// Three ways to declare variables let name = "Alice"; // Can be changed later const age = 25; // Cannot be changed (constant) var city = "Delhi"; // Old way (avoid in modern JS) // Updating a let variable name = "Bob"; // β Works fine // Trying to update const // age = 30; // β Error! Constants can't change console.log(name); // "Bob" console.log(age); // 25
let β Your go-to choice
Use let when the value needs to change over time.
let score = 0; score = score + 10; // score is now 10 score += 5; // score is now 15 console.log(score); // 15
const β Lock it down
Use const for values that never change. It's the safest default.
const PI = 3.14159; const MAX_USERS = 100; const APP_NAME = "MyApp"; // Good rule: Use const by default // Switch to let only when you need to reassign
var β The old way (avoid it)
var has confusing scope rules and was used before 2015. Modern JS
uses let and const.
// var is "hoisted" β confusing behavior console.log(x); // undefined (no error!) var x = 5; // let would throw an error here // console.log(y); // ReferenceError let y = 5; // Stick to let/const β
Variable Naming Rules
| Rule | Valid | Invalid |
|---|---|---|
| Start with letter, _ or $ | name, _id, $el |
1name, -val |
| No spaces | myName, my_name |
my name |
| Case sensitive | Name β name |
β |
| No reserved keywords | myLet |
let, const |
| Use camelCase (convention) | firstName |
firstname (works but ugly) |
7 Primitive Types
| Type | Example | Description |
|---|---|---|
| String | "Hello", 'World' |
Text, wrapped in quotes |
| Number | 42, 3.14, -7 |
All numbers (int + float) |
| Boolean | true, false |
Yes/No, On/Off |
| Undefined | undefined |
Variable declared, not assigned |
| Null | null |
Intentionally empty value |
| BigInt | 9007199254740991n |
Huge integers |
| Symbol | Symbol("id") |
Unique identifiers |
1 Complex Type
// Object β key-value pairs const person = { name: "Alice", age: 25, isStudent: true }; // Array β ordered list (also an object!) const colors = ["red", "green", "blue"]; // typeof β check the type of any value console.log(typeof "hello"); // "string" console.log(typeof 42); // "number" console.log(typeof true); // "boolean" console.log(typeof undefined);// "undefined" console.log(typeof null); // "object" β famous JS bug!
typeof null returns
"object" β this is a known bug in JS from 1995. It was kept for backward
compatibility and never fixed.| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 10 - 4 |
6 |
* |
Multiplication | 3 * 4 |
12 |
/ |
Division | 15 / 4 |
3.75 |
% |
Modulus (remainder) | 10 % 3 |
1 |
** |
Exponent | 2 ** 8 |
256 |
++ |
Increment | x++ |
x + 1 |
-- |
Decrement | x-- |
x - 1 |
let a = 10, b = 3; console.log(a + b); // 13 console.log(a % b); // 1 (remainder of 10Γ·3) console.log(2 ** 10); // 1024 // The + with strings = concatenation! console.log("Hello" + " World"); // "Hello World" console.log("Age: " + 25); // "Age: 25"
| Operator | Means | Example |
|---|---|---|
= |
Assign | x = 5 |
+= |
x = x + y |
x += 3 |
-= |
x = x - y |
x -= 2 |
*= |
x = x * y |
x *= 4 |
/= |
x = x / y |
x /= 2 |
%= |
x = x % y |
x %= 3 |
**= |
x = x ** y |
x **= 2 |
| Operator | Name | Returns true when⦠|
|---|---|---|
&& |
AND | BOTH sides are true |
|| |
OR | AT LEAST one side is true |
! |
NOT | Opposite of the value |
let isAdult = true; let hasID = false; console.log(isAdult && hasID); // false (both needed) console.log(isAdult || hasID); // true (one is enough) console.log(!isAdult); // false (flip it) // ?? (Nullish Coalescing) β new & useful! let user = null; console.log(user ?? "Guest"); // "Guest" (fallback for null/undefined)
Ternary β Shortcut if/else
Format: condition ? valueIfTrue : valueIfFalse
let age = 20; // Regular if/else let status; if (age >= 18) { status = "Adult"; } else { status = "Minor"; } // Ternary β same thing in one line! let status2 = age >= 18 ? "Adult" : "Minor"; console.log(status); // "Adult" console.log(status2); // "Adult"
Creating Strings β 3 Ways
let s1 = "Double quotes"; // Regular let s2 = 'Single quotes'; // Regular let s3 = `Template literal`; // Backtick β BEST WAY const name = "Alice"; const age = 25; // Template literals β embed variables directly! let msg = `Hello, my name is ${name} and I am ${age} years old.`; console.log(msg); // "Hello, my name is Alice and I am 25 years old." // Can even do math inside ${}! console.log(`Next year I'll be ${age + 1}`); // "Next year I'll be 26"
Essential String Methods
| Method | What it does | Example |
|---|---|---|
.length |
Number of characters | "hello".length β 5 |
.toUpperCase() |
ALL CAPS | "hi".toUpperCase() β "HI" |
.toLowerCase() |
all lowercase | "HI".toLowerCase() β "hi" |
.trim() |
Remove whitespace | " hi ".trim() β "hi" |
.includes() |
Check if text exists | "hello".includes("ell") β true |
.startsWith() |
Starts with? | "hello".startsWith("he") β true |
.endsWith() |
Ends with? | "hello".endsWith("lo") β true |
.slice(start, end) |
Extract part | "hello".slice(1,3) β "el" |
.replace(old, new) |
Replace text | "hi bob".replace("bob","alice") |
.split(separator) |
Split into array | "a,b,c".split(",") β ["a","b","c"] |
.indexOf() |
Position of text | "hello".indexOf("l") β 2 |
.repeat(n) |
Repeat n times | "ha".repeat(3) β "hahaha" |
const str = " Hello, JavaScript World! "; console.log(str.trim()); // "Hello, JavaScript World!" console.log(str.trim().length); // 24 console.log(str.includes("Java")); // true console.log(str.slice(8, 18)); // "JavaScript" // String is indexed like an array console.log(str[2]); // "H" (index starts at 0!) console.log(str.at(-1)); // " " (last char)
Number Basics
// All of these are the same "Number" type let integer = 42; let float = 3.14; let negative = -100; let scientific = 1.5e6; // 1,500,000 // Special number values console.log(1 / 0); // Infinity console.log(-1 / 0); // -Infinity console.log("abc" * 2); // NaN (Not a Number) console.log(isNaN("abc" * 2)); // true // Famous floating point issue console.log(0.1 + 0.2); // 0.30000000000000004 β ! console.log((0.1 + 0.2).toFixed(1)); // "0.3" β fixed
Useful Number Methods
| Method | What it does | Example |
|---|---|---|
.toFixed(n) |
Round to n decimals (returns string) | (3.14159).toFixed(2) β "3.14" |
.toString() |
Convert to string | (255).toString(16) β "ff" |
Number.isInteger() |
Is it a whole number? | Number.isInteger(4.0) β true |
Number.isFinite() |
Is it finite? | Number.isFinite(Infinity) β false |
Number.isNaN() |
Strictly is NaN? | Number.isNaN(NaN) β true |
Number.MAX_SAFE_INTEGER |
Largest safe integer | 9007199254740991 |
The Math object is a built-in JS object with mathematical constants and
functions. You don't need to import anything β it's always available.
// Constants console.log(Math.PI); // 3.141592653589793 console.log(Math.E); // 2.718281828459045 // Rounding console.log(Math.round(4.6)); // 5 (nearest) console.log(Math.floor(4.9)); // 4 (round down) console.log(Math.ceil(4.1)); // 5 (round up) console.log(Math.trunc(4.9)); // 4 (remove decimal) // Power & Roots console.log(Math.pow(2, 10)); // 1024 console.log(Math.sqrt(144)); // 12 console.log(Math.cbrt(27)); // 3 // Min / Max / Absolute console.log(Math.max(3, 7, 1)); // 7 console.log(Math.min(3, 7, 1)); // 1 console.log(Math.abs(-42)); // 42 // Random number between 0 and 1 console.log(Math.random()); // e.g. 0.7351823... // Random integer between min and max (inclusive) function randInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(randInt(1, 6)); // Dice roll: 1β6
IEEE 754 β 64-bit Double Precision
JavaScript stores ALL numbers as 64-bit floating point (IEEE 754). Think of it like scientific notation in binary β there's a limit to precision.
Sign + 11 bits
Exponent + 52 bits
Fraction = 64 bits total
Why 0.1 + 0.2 β 0.3
0.1 in binary is a repeating decimal, like 1/3 in base-10. The stored approximation causes rounding errors in arithmetic.
console.log(0.1 + 0.2); // 0.30000000000000004 // Fix 1: toFixed (0.1 + 0.2).toFixed(1) // "0.3" // Fix 2: Multiply to integers (0.1 * 10 + 0.2 * 10) / 10 // 0.3
Safe Integer Limits
JS can represent integers exactly only up to 2β΅Β³ - 1. Beyond that, numbers lose precision.
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991 console.log(9007199254740991 + 1); // 9007199254740992 β console.log(9007199254740991 + 2); // 9007199254740992 β WRONG! // For huge numbers, use BigInt: const big = 9007199254740991n + 2n; console.log(big); // 9007199254740993n β
// To Number console.log(Number("42")); // 42 console.log(Number("3.14")); // 3.14 console.log(Number("")); // 0 console.log(Number("abc")); // NaN console.log(Number(true)); // 1 console.log(Number(false)); // 0 console.log(Number(null)); // 0 console.log(Number(undefined)); // NaN // To String console.log(String(42)); // "42" console.log(String(true)); // "true" console.log(String(null)); // "null" console.log((255).toString(16)); // "ff" (hex!) // To Boolean console.log(Boolean(0)); // false console.log(Boolean("")); // false console.log(Boolean(null)); // false console.log(Boolean(undefined)); // false console.log(Boolean(NaN)); // false console.log(Boolean("hello")); // true console.log(Boolean(42)); // true
0, "",
null, undefined, NaN,
false. Everything else is truthy!JS secretly converts types for you (sometimes badly!)
// + with string = concatenation! console.log("5" + 3); // "53" (string wins) console.log("5" - 3); // 2 (number wins) console.log("5" * 3); // 15 console.log(true + true); // 2 console.log(true + 1); // 2 console.log("6" / "2"); // 3 // VERY confusing stuff: console.log([] + []); // "" console.log([] + {}); // "[object Object]" console.log(+"42"); // 42 (unary + converts to number)
Number(),
String(), Boolean(). It makes code predictable.
Parsing Numbers from Strings
// parseInt β extract an integer console.log(parseInt("42px")); // 42 (stops at non-number) console.log(parseInt("3.7")); // 3 (truncates decimal) console.log(parseInt("ff", 16)); // 255 (hex base) console.log(parseInt("abc")); // NaN // parseFloat β extract a decimal console.log(parseFloat("3.14abc")); // 3.14 console.log(parseFloat(" 12.5 ")); // 12.5 // Number() vs parseInt() console.log(Number("42px")); // NaN console.log(parseInt("42px")); // 42
Comparison Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal (with coercion) | "5" == 5 |
true β οΈ |
=== |
Strictly equal (no coercion) | "5" === 5 |
false β |
!= |
Not equal (with coercion) | "5" != 5 |
false β οΈ |
!== |
Strictly not equal | "5" !== 5 |
true β |
> |
Greater than | 10 > 5 |
true |
< |
Less than | 3 < 7 |
true |
>= |
Greater than or equal | 5 >= 5 |
true |
<= |
Less than or equal | 4 <= 3 |
false |
== vs === β The Big Rule
// == converts types before comparing (DANGEROUS!) console.log(0 == false); // true β WHAT?! console.log("" == false); // true β ! console.log(null == undefined);// true β ! console.log("1" == 1); // true // === compares value AND type (SAFE) console.log(0 === false); // false β console.log("" === false); // false β console.log("1" === 1); // false β console.log(1 === 1); // true β // NaN is special β not equal to anything, even itself! console.log(NaN === NaN); // false β ! console.log(Number.isNaN(NaN));// true β correct way
=== and
!==. Never use == or !=. The loose equality
operator hides bugs.A loop runs a block of code repeatedly until a condition becomes false. Instead of writing the same code 100 times, write it once and loop 100 times.
for β when you know how many times
Format: for (initialize; condition; update)
// Count 1 to 5 for (let i = 1; i <= 5; i++) { console.log(i); } // 1, 2, 3, 4, 5 // Loop over an array const fruits = ["apple", "banana", "cherry"]; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } // "apple", "banana", "cherry" // Count backwards for (let i = 5; i >= 1; i--) { console.log(i); // 5, 4, 3, 2, 1 }
while β when you don't know how many times
let count = 0; while (count < 5) { console.log("Count: " + count); count++; } // Count: 0, Count: 1, ... Count: 4 // Real example: keep asking until valid input let password = ""; while (password !== "secret123") { password = prompt("Enter password:"); } console.log("Access granted!");
do...while β runs at least once
The code inside runs first, then checks the condition.
let n = 0; do { console.log("Runs at least once! n =" + n); n++; } while (n < 3); // n = 0, n = 1, n = 2 // Even when condition is false from start: let x = 10; do { console.log("This runs once anyway!"); } while (x < 5); // false but code ran!
for...of β best way to loop arrays/strings
const colors = ["red", "green", "blue"]; for (const color of colors) { console.log(color); } // "red", "green", "blue" // Works on strings too! for (const char of "hello") { console.log(char); } // h, e, l, l, o // Get index too with entries() for (const [i, val] of colors.entries()) { console.log(i, val); } // 0 "red", 1 "green", 2 "blue"
for...in β loop over object keys
const person = { name: "Alice", age: 25, city: "Paris" }; for (const key in person) { console.log(key, "β", person[key]); } // name β Alice // age β 25 // city β Paris
for...of
for arrays. Use for...in for objects. Use for
when you need the index.break & continue β control the flow
// break β EXIT the loop entirely for (let i = 0; i < 10; i++) { if (i === 5) break; // stop when i = 5 console.log(i); } // 0, 1, 2, 3, 4 // continue β SKIP current iteration for (let i = 0; i < 6; i++) { if (i % 2 === 0) continue; // skip even numbers console.log(i); } // 1, 3, 5
π¦ Variables
let x = 5; const PI = 3.14; var old = "avoid";
π·οΈ Data Types
"text" // String 42 // Number true // Boolean null // Null undefined // Undefined
βοΈ Operators
+ - * / % **
+= -= *= /=
=== !== > < >= <=
&& || ! ??
? : // ternary
π¬ Template Literals
const n = "Alice"; `Hello, ${n}!` `Sum: ${2 + 3}`
π Conversion
Number("42") // 42 String(42) // "42" Boolean(0) // false parseInt("5px") // 5
π Loops
for (let i=0; i<5; i++) {} while (cond) {} for (const x of arr) {} for (const k in obj) {}
π Math
Math.round(4.6) // 5 Math.floor(4.9) // 4 Math.random() // 0-1 Math.max(1,2,3) // 3
π¬ String Methods
s.length s.toUpperCase() s.includes("x") s.slice(0,5) s.trim()
βοΈ Comparison
// Always use === "5" === 5 // false β "5" == 5 // true β οΈ isNaN(NaN) // true
π Loop Control
break; // exit loop continue; // skip iteration // do...while do { } while (cond);
πΎ Number Storage
// 64-bit IEEE 754 0.1 + 0.2 // 0.300...04! MAX_SAFE = 9007199254740991 BigInt: 100n + 200n
π Common Gotchas
typeof null // "object" bug NaN === NaN // false! 0.1+0.2 β 0.3 // float! "5" + 3 = "53" // coerce
1. JS Fundamentals Beginner
Variables, Data Types, Operators, Strings, Numbers, Loops, Conversion β everything on this page. You're here! β
2. Functions & Scope Beginner
Regular functions, arrow functions, parameters, return values, local vs global scope, closures basics.
3. Arrays & Objects Beginner
Array methods (map, filter, reduce, forEach), object manipulation, destructuring, spread operator.
4. DOM Manipulation Core
Selecting HTML elements, changing content/styles, creating/removing elements, event listeners, forms.
5. Async JavaScript Core
Callbacks, Promises, async/await, the Event Loop, setTimeout/setInterval, fetch API.
6. ES6+ Modern Features Core
Arrow functions, template literals, destructuring, modules (import/export), optional chaining, nullish coalescing.
7. OOP & Prototypes Advanced
Classes, constructors, inheritance, prototype chain, this keyword, static methods.
8. APIs & JSON Advanced
Fetch API, REST APIs, JSON.parse/stringify, error handling, CORS basics.
9. Pick a Framework Advanced
React, Vue, or Svelte for frontend. Node.js + Express for backend. Choose based on your goal.