JavaScript from Zero to Hero
Learn JavaScript step by step! From complete beginner to confident coder. Practice with interactive examples - no prior coding experience needed!
๐ฎ How to Learn JavaScript Here
- Read the explanation for each concept
- Look at the code example in the editor
- Click โถ Run Code to see what it does
- Try changing the code and run it again!
- Use quick buttons to try different examples
- Press Ctrl + Enter to run code quickly
Basics
Variables, Data Types, Console
2๏ธโฃOperators
Math, Comparison, Logic
3๏ธโฃConditionals
if/else, switch, ternary
4๏ธโฃLoops
for, while, do-while
๐Break & Continue
Loop Control, Skip, Exit
5๏ธโฃFunctions
Basic, Arrow, Parameters
6๏ธโฃArrays
Create, Access, Methods
7๏ธโฃArray Methods
map, filter, reduce, find
8๏ธโฃObjects
Properties, Methods, this
9๏ธโฃStrings
Methods, Template Literals
๐ขNumbers & Math
parseInt, Math methods
๐Date & Time
Date object, formatting
Scope & Hoisting
var, let, const, TDZ
๐Closures Deep Dive
Lexical scope, private data
๐this & Context
call, apply, bind
๐ฏDestructuring
Arrays, Objects, Rest/Spread
โณAsync JavaScript
Callbacks, Promises, async/await
๐Event Loop
Microtasks, Macrotasks, Queue
๐Fetch API
HTTP requests, JSON, APIs
๐๏ธLocal Storage
Store data in browser
โ ๏ธError Handling
try/catch, throw, Error types
๐งฉHigher-Order & Currying
Callbacks, Partial application
๐ฆModules
import, export, dynamic imports
๐JSON
Parse, Stringify, Data exchange
Classes & OOP
class, constructor, inheritance
๐ญPrototypes
Prototype chain, inheritance
๐ฎSymbols & Iterators
Symbol, Iterator protocol
๐กGenerators
function*, yield, async generators
๐บ๏ธMap & Set
Map, Set, WeakMap, WeakSet
๐ชProxy & Reflect
Metaprogramming, traps
๐งฌRegular Expressions
Patterns, match, replace
โกPerformance
Optimization, memory, BigO
๐ก๏ธSecurity
XSS, CSRF, best practices
Memory Management
Garbage collection, leaks, V8
โ๏ธV8 Engine Internals
JIT, hidden classes, optimization
๐ณDOM & Browser Events
Bubbling, capturing, delegation
๐ขFunctional Programming
Pure functions, immutability
๐ฅ๏ธNode.js Advanced
EventEmitter, Streams, Workers
๐WeakMap & WeakSet
Private data, memory efficiency
โฑ๏ธMicrotasks vs Macrotasks
Task queue priority
๐Deep vs Shallow Copy
Object cloning, references
๐จDesign Patterns
Singleton, Factory, Observer
JavaScript Basics
JavaScript is a programming language that makes websites interactive! It's like giving instructions to your computer.
HTML
Structure (skeleton)
CSS
Style (clothes)
JavaScript
Behavior (brain)
console.log() is how we print messages. It's like telling your computer to "speak" and show something!
๐ Key Point:
Everything inside console.log() will appear in the console output!
Click "Run Code" or press Ctrl+Enter to see output...
A variable is like a box where you store information. You give the box a name, and put something inside it!
letCan be changed later
Use for most variables
constCannot be changed
Use for fixed values
varOld way (avoid)
Don't use anymore
๐ Key Point:
Variable names should describe what's inside! Use camelCase like: myName, userAge, isLoggedIn
Click "Run Code" or press Ctrl+Enter to see output...
JavaScript has different types of data. Think of it like different kinds of things you can put in boxes!
StringText in quotes
"Hello", 'World'NumberAny number
42, 3.14, -10Booleantrue or false
true, falseArrayList of items
[1, 2, 3]ObjectCollection of data
{name: "Jo"}undefined/nullEmpty/nothing
undefined, nullClick "Run Code" or press Ctrl+Enter to see output...
Operators
Just like a calculator! JavaScript can do all kinds of math.
+Add
5 + 3 = 8
-Subtract
10 - 4 = 6
*Multiply
6 * 7 = 42
/Divide
20 / 5 = 4
%Remainder
10 % 3 = 1
**Power
2 ** 3 = 8
++Add 1
x++ โ x+1
--Minus 1
x-- โ x-1
Click "Run Code" or press Ctrl+Enter to see output...
Compare values and get true or false!
===Equal to
5 === 5 โ true
!==Not equal
5 !== 3 โ true
>Greater than
5 > 3 โ true
<Less than
3 < 5 โ true
>=Greater or equal
5 >= 5 โ true
<=Less or equal
3 <= 5 โ true
โ ๏ธ Important:
Always use === (three equals), not == (two equals). Three equals is safer!
Click "Run Code" or press Ctrl+Enter to see output...
Combine multiple conditions together!
&&AND
Both must be true
true && true = true
true && false = false
||OR
At least one true
true || false = true
false || false = false
!NOT
Flips the value
!true = false
!false = true
Click "Run Code" or press Ctrl+Enter to see output...
Conditionals (if/else)
if/else lets your code make decisions! Like asking: "IF this is true, do this, ELSE do that"
if (condition) {
// do this if condition is true
} else if (another condition) {
// do this if first was false, but this is true
} else {
// do this if all conditions are false
}๐ Key Point:
The condition inside if() is checked. If it's true, the code inside {} runs!
Click "Run Code" or press Ctrl+Enter to see output...
A shorter way to write simple if/else in one line!
condition ? valueIfTrue : valueIfFalse
// Example:
let status = age >= 18 ? "adult" : "minor";Click "Run Code" or press Ctrl+Enter to see output...
When you have many specific values to check, use switch!
Click "Run Code" or press Ctrl+Enter to see output...
Loops - Repeat Actions
Loops let you run the same code multiple times without writing it again and again!
forWhen you know how many times
whileWhile condition is true
for...ofLoop through arrays
for (start; condition; step) {
// code to repeat
}
// Example:
for (let i = 0; i < 5; i++) {
console.log(i); // prints 0, 1, 2, 3, 4
}let i = 0Start: where to begin
i < 5Condition: when to stop
i++Step: how to change
Click "Run Code" or press Ctrl+Enter to see output...
Keeps running while the condition is true. Be careful of infinite loops!
while (condition) {
// code runs while condition is true
// make sure to change the condition!
}Click "Run Code" or press Ctrl+Enter to see output...
Break & Continue - Loop Control
break immediately exits the loop, skipping all remaining iterations!
When to use break:
- โข When you found what you're looking for
- โข To exit an infinite loop with a condition
- โข When an error or special case is detected
Click "Run Code" or press Ctrl+Enter to see output...
continue skips the rest of the current iteration and jumps to the next one!
When to use continue:
- โข Skip invalid or unwanted items
- โข Filter out certain conditions
- โข Clean data processing
Click "Run Code" or press Ctrl+Enter to see output...
Labels let you break or continue outer loops from inside nested loops!
Click "Run Code" or press Ctrl+Enter to see output...
Functions - Reusable Code
A function is like a recipe - a set of instructions you can use again and again!
Define Once
Write the code once
Use Many Times
Call it whenever needed
Return Results
Get values back
Click "Run Code" or press Ctrl+Enter to see output...
Arrow functions are a shorter, modern way to write functions!
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function (same thing!)
const add = (a, b) => a + b;
// Arrow function with one parameter
const double = x => x * 2;
// Arrow function with body
const greet = (name) => {
console.log("Hello " + name);
return "Greeted!";
};Click "Run Code" or press Ctrl+Enter to see output...
Arrays - Lists of Data
An array is a list that holds multiple values! Like a shopping list or a playlist.
// Array syntax
let fruits = ["๐", "๐", "๐", "๐"];
// Index: 0 1 2 3
// Access by index (starts at 0!)
fruits[0] // "๐" (first item)
fruits[2] // "๐" (third item)๐ Key Point:
Array indexes start at 0, not 1! The first item is at index 0.
Click "Run Code" or press Ctrl+Enter to see output...
Powerful Array Methods
map() creates a new array by transforming each item!
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
// Result: [2, 4, 6, 8, 10]Click "Run Code" or press Ctrl+Enter to see output...
filter() creates a new array with only the items that pass a test!
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
// Result: [2, 4, 6]Click "Run Code" or press Ctrl+Enter to see output...
reduce() takes all items and combines them into a single value!
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, n) => total + n, 0);
// Result: 15
// reduce(callback, startValue)
// callback: (accumulator, currentValue) => newAccumulatorClick "Run Code" or press Ctrl+Enter to see output...
find() returns the first item that matches. findIndex() returns its position.
Click "Run Code" or press Ctrl+Enter to see output...
You can chain map(), filter(), and more together!
Click "Run Code" or press Ctrl+Enter to see output...
Objects - Organize Data
An object stores data in key-value pairs. Like a person with name, age, job!
const person = {
name: "John", // key: value
age: 25,
isStudent: true,
hobbies: ["coding", "gaming"]
};
// Access with dot or brackets
person.name // "John"
person["age"] // 25Click "Run Code" or press Ctrl+Enter to see output...
Objects can have functions too! They're called methods.
Click "Run Code" or press Ctrl+Enter to see output...
Get all keys, values, or key-value pairs from an object!
Click "Run Code" or press Ctrl+Enter to see output...
String Methods
Strings have many useful methods for working with text!
.lengthCount characters
.toUpperCase()MAKE UPPERCASE
.toLowerCase()make lowercase
.trim()Remove spaces
.split()Split into array
.includes()Check if contains
.startsWith()Check start
.endsWith()Check end
.replace()Replace text
Click "Run Code" or press Ctrl+Enter to see output...
Use backticks (`) to create strings with variables inside! Much easier than + concatenation.
const name = "Alice";
const age = 25;
// Old way (concatenation)
console.log("Hello, " + name + "! You are " + age + " years old.");
// New way (template literals) - Much cleaner! โจ
console.log(`Hello, ${name}! You are ${age} years old.`);Click "Run Code" or press Ctrl+Enter to see output...
Numbers & Math
JavaScript has powerful built-in methods for working with numbers and mathematical operations!
parseInt()String to integer
parseFloat()String to decimal
Number()Convert to number
.toFixed(n)Round to n decimals
isNaN()Check if Not a Number
isFinite()Check if finite
Click "Run Code" or press Ctrl+Enter to see output...
Date & Time
The Date object lets you work with dates and times in JavaScript!
getFullYear()Year (2024)
getMonth()Month (0-11)
getDate()Day (1-31)
getDay()Weekday (0-6)
getHours()Hours (0-23)
getMinutes()Minutes (0-59)
getSeconds()Seconds (0-59)
getTime()Milliseconds
Click "Run Code" or press Ctrl+Enter to see output...
Level up your skills with advanced concepts!
Scope & Hoisting
Scope determines where variables are accessible in your code.
Global Scope
Accessible everywhere
Function Scope
Only inside function
Block Scope
Inside { } with let/const
Click "Run Code" or press Ctrl+Enter to see output...
Closures Deep Dive
A closure is when a function "remembers" variables from its outer scope even after that scope has finished executing. This is one of the most powerful features in JavaScript!
Lexical Scope
Functions look up variables where they were defined, not where they're called
Data Privacy
Closures can create truly private variables
Click "Run Code" or press Ctrl+Enter to see output...
this & Context
The this keyword refers to the object that is executing the current function. Its value depends on HOW the function is called, not where it's defined!
Global
this = window (browser)
Method
this = object
Arrow
this = lexical (parent)
call/apply/bind
this = explicit
Click "Run Code" or press Ctrl+Enter to see output...
Destructuring
Destructuring lets you extract values from arrays and objects into variables!
Click "Run Code" or press Ctrl+Enter to see output...
Async JavaScript
JavaScript is single-threaded but can handle async operations without blocking!
Callbacks
Old way (callback hell ๐ฑ)
Promises
Better! .then() chains
async/await
Best! Clean syntax โจ
Click "Run Code" or press Ctrl+Enter to see output...
Event Loop
The Event Loop is how JavaScript handles asynchronous operations despite being single-threaded. It's essential knowledge for senior developers!
Call Stack
Executes synchronous code (LIFO)
Web APIs
Handles async operations
Task Queue
setTimeout, events (macrotasks)
Microtask Queue
Promises, queueMicrotask
Click "Run Code" or press Ctrl+Enter to see output...
Fetch API
The fetch() API lets you make HTTP requests to servers and APIs!
Common HTTP Methods:
Click "Run Code" or press Ctrl+Enter to see output...
Local Storage
localStorage lets you store data in the browser that persists even after closing!
localStorage
Persists forever (until cleared)
sessionStorage
Cleared when tab closes
Click "Run Code" or press Ctrl+Enter to see output...
Error Handling
try/catch lets you handle errors without crashing your program!
tryCode that might fail
catchHandle the error
finallyAlways runs
Click "Run Code" or press Ctrl+Enter to see output...
Higher-Order Functions & Currying
A higher-order function either takes a function as an argument or returns a function!Currying transforms a function with multiple arguments into a sequence of functions.
Click "Run Code" or press Ctrl+Enter to see output...
Modules
Modules let you split code into separate files and import/export between them!
exportMake code available to other files
importUse code from other files
Click "Run Code" or press Ctrl+Enter to see output...
JSON
JSON is the standard format for sending data between servers and web apps!
JSON.stringify()Object โ String
JSON.parse()String โ Object
Click "Run Code" or press Ctrl+Enter to see output...
Master the language with expert-level concepts!
Classes & OOP
Classes are blueprints for creating objects with shared properties and methods!
Click "Run Code" or press Ctrl+Enter to see output...
Prototypes
Every JavaScript object has a prototype - another object it inherits from!
Click "Run Code" or press Ctrl+Enter to see output...
Symbols & Iterators
Symbols are unique, immutable identifiers.Iterators define how objects are looped over!
Click "Run Code" or press Ctrl+Enter to see output...
Generators
Generators are functions that can be paused and resumed, producing a sequence of values!
Click "Run Code" or press Ctrl+Enter to see output...
Map & Set
Map and Set are more powerful than plain objects and arrays!
Map
Key-value pairs with any type as key
Set
Collection of unique values
Click "Run Code" or press Ctrl+Enter to see output...
Proxy & Reflect
Proxy lets you intercept and customize operations on objects!
Click "Run Code" or press Ctrl+Enter to see output...
Regular Expressions
RegEx (Regular Expressions) are patterns for matching text!
\\d digit\\w word\\s space. any+ 1+* 0+? 0-1{n} n timesClick "Run Code" or press Ctrl+Enter to see output...
Performance
Understanding performance helps you write faster, more efficient code!
Click "Run Code" or press Ctrl+Enter to see output...
Security Best Practices
Security is crucial! Learn common vulnerabilities and how to prevent them.
XSS
Cross-Site Scripting
Injection
SQL/Code Injection
CSRF
Cross-Site Request Forgery
Click "Run Code" or press Ctrl+Enter to see output...
Memory Management
Understanding memory management is crucial for building performant applications. JavaScript uses automatic garbage collection, but memory leaks can still occur!
Stack
Primitives, function calls (fast, fixed size)
Heap
Objects, arrays (dynamic, GC managed)
Garbage Collection
Mark-and-sweep algorithm
Click "Run Code" or press Ctrl+Enter to see output...
V8 Engine Internals
V8 is Google's JavaScript engine used in Chrome and Node.js. Understanding how it works helps you write faster code!
Parser
JS โ AST
Ignition
Interpreter (bytecode)
TurboFan
JIT Compiler (optimized)
Deoptimization
Back to interpreter
Click "Run Code" or press Ctrl+Enter to see output...
DOM & Browser Events
Understanding event propagation (bubbling & capturing) and efficient DOM manipulation is essential for building performant web applications.
Capturing โฌ๏ธ
Window โ Document โ Element (top-down)
Target ๐ฏ
Event reaches the clicked element
Bubbling โฌ๏ธ
Element โ Document โ Window (bottom-up)
Click "Run Code" or press Ctrl+Enter to see output...
Functional Programming
Functional programming (FP) is a paradigm that treats computation as evaluation of mathematical functions. It emphasizes immutability and pure functions.
Pure Functions
Same input โ same output, no side effects
Immutability
Never mutate data, create new copies
First-Class Fns
Functions as values, arguments, returns
Declarative
What to do, not how to do it
Click "Run Code" or press Ctrl+Enter to see output...
Node.js Advanced
Node.js has powerful features for building scalable server-side applications. Understanding EventEmitter, Streams, and Worker Threads is essential!
EventEmitter
Pub/sub pattern for events
Streams
Process data chunk by chunk
Worker Threads
True multi-threading in Node
Click "Run Code" or press Ctrl+Enter to see output...
WeakMap & WeakSet
WeakMap and WeakSet hold weak references to objects. If an object has no other references, it can be garbage collected even if it's in a WeakMap!
WeakMap
Keys must be objects, values can be anything
WeakSet
Only stores objects, no duplicates
Click "Run Code" or press Ctrl+Enter to see output...
Microtasks vs Macrotasks
Understanding the difference between microtasks and macrotasks is crucial for predicting JavaScript execution order. Microtasks always run before macrotasks!
Microtasks (High Priority)
- โข Promise.then/catch/finally
- โข queueMicrotask()
- โข MutationObserver
Macrotasks (Lower Priority)
- โข setTimeout/setInterval
- โข setImmediate (Node)
- โข I/O, UI rendering
Click "Run Code" or press Ctrl+Enter to see output...
Deep vs Shallow Copy
Understanding the difference between shallow and deep copying is essential for avoiding unexpected mutations!
Shallow Copy
Copies top-level properties only. Nested objects are shared!
Deep Copy
Recursively copies all nested objects. Completely independent!
Click "Run Code" or press Ctrl+Enter to see output...
Design Patterns
Design patterns are proven solutions to common programming problems. They make code more maintainable, reusable, and scalable.
Creational
Singleton, Factory, Builder
Structural
Module, Decorator, Facade
Behavioral
Observer, Mediator, Strategy
Click "Run Code" or press Ctrl+Enter to see output...
Variables
let x = 10;const PI = 3.14;Arrays
let arr = [1, 2, 3];arr.push(4);Objects
let obj = {name: "Jo"};obj.name;Functions
function add(a,b){ย ย return a + b;}Arrow Functions
const add = (a,b) => a + b;Array Methods
arr.map(x => x * 2)arr.filter(x => x > 5)arr.reduce((a,b) => a+b)Congratulations!
You've learned the fundamentals of JavaScript! Keep practicing and building projects!
๐ก Pro tip: The best way to learn is by doing. Try modifying all the examples above!