Welcome to JavaScript Learning Hub

Your complete guide to mastering JavaScript from scratch

How This Works

1

Learn Concepts

Go through each section step by step. Read the explanations and examples carefully.

2

Practice Code

Use the Code Playground to write and test your code. Experiment with different examples.

3

Reference

Use the Cheat Sheet as a quick reference. Download it for offline use.

4

Explore

Check out external resources for deeper learning and advanced topics.

Introduction to JavaScript

What is JavaScript?

JavaScript is a powerful, flexible programming language that's one of the core technologies of the World Wide Web, alongside HTML and CSS.

Why Learn JavaScript?

  • Versatile: Works in browsers, servers (Node.js), mobile apps, and more
  • Popular: One of the most used programming languages worldwide
  • Essential: Required for modern web development
  • Job Market: High demand for JavaScript developers
  • Community: Large, supportive community and extensive resources

What Can JavaScript Do?

  • Create interactive websites and web applications
  • Handle user interactions (clicks, forms, etc.)
  • Manipulate HTML and CSS dynamically
  • Make web pages responsive and interactive
  • Build backend services with Node.js
  • Develop mobile and desktop applications

Getting Started

Setting Up JavaScript

You don't need any special setup to start learning JavaScript! You can run JavaScript in your browser's console or create an HTML file.

Method 1: Browser Console

  1. Open your web browser (Chrome, Firefox, Edge, etc.)
  2. Press F12 or right-click and select "Inspect"
  3. Click on the "Console" tab
  4. Type JavaScript code and press Enter

Method 2: HTML File

<!DOCTYPE html>
<html>
<head>
    <title>My First JavaScript</title>
</head>
<body>
    <script>
        console.log("Hello, JavaScript!");
    </script>
</body>
</html>

Method 3: External JavaScript File

<script src="script.js"></script>

Variables & Data Types

Variables

Variables are containers that store data values. In JavaScript, you can declare variables using:

  • var - Function-scoped (older way)
  • let - Block-scoped (modern way)
  • const - Block-scoped, cannot be reassigned

Examples:

// Using 'let' - modern way, block-scoped
// Can be reassigned (changed later)
let name = "John";  // Declares variable 'name' with string value
let age = 25;       // Declares variable 'age' with number value

// Using 'const' - for constants (values that won't change)
// Cannot be reassigned, must initialize with value
const pi = 3.14159;      // Constant for mathematical value
const greeting = "Hello"; // Constant string value

// Using 'var' - older style, function-scoped
// Avoid using in modern JavaScript (use 'let' instead)
var city = "New York"; // Function-scoped variable

Data Types

JavaScript has several data types:

String

"Hello" or 'World'

Number

42 or 3.14

Boolean

true or false

Null

null

Undefined

undefined

Object

{name: "John"}

Array

[1, 2, 3]

Type Checking:

typeof "hello"  // "string"
typeof 42       // "number"
typeof true     // "boolean"
typeof null     // "object" (this is a bug!)
typeof undefined // "undefined"

Operators

Arithmetic Operators

// Declare and initialize two variables
let a = 10; // First number
let b = 3;  // Second number

// Basic arithmetic operations
a + b  // Addition: 10 + 3 = 13
a - b  // Subtraction: 10 - 3 = 7
a * b  // Multiplication: 10 × 3 = 30
a / b  // Division: 10 ÷ 3 = 3.333...
a % b  // Modulus: remainder of 10 ÷ 3 = 1
a ** b // Exponentiation: 10 to power of 3 = 1000

// Increment operators
// Post-increment: use value first, then increment
a++    // Returns 10, then a becomes 11
// Pre-increment: increment first, then use value
++a    // a becomes 11, then returns 11

// Decrement operators
a--    // Post-decrement: returns value, then decreases
--a    // Pre-decrement: decreases first, then returns

Assignment Operators

// Initialize variable
let x = 5;

// Compound assignment operators (shorthand)
// Adds 3 to x and assigns result back to x
x += 3  // Same as: x = x + 3  → x becomes 8

// Subtracts 2 from x and assigns result back
x -= 2  // Same as: x = x - 2  → x becomes 6

// Multiplies x by 2 and assigns result back
x *= 2  // Same as: x = x * 2  → x becomes 12

// Divides x by 3 and assigns result back
x /= 3  // Same as: x = x / 3  → x becomes 4

// Modulus: remainder after division
x %= 3  // Same as: x = x % 3  → x becomes 1

Comparison Operators

// Equality operators
// Loose equality: converts types if needed (not recommended)
5 == 5    // true - both are 5
5 == "5"  // true - converts string to number

// Strict equality: checks value AND type (recommended)
5 === 5   // true - same value and type (number === number)
5 === "5" // false - same value but different types

// Inequality operators
5 != 3    // true - 5 is not equal to 3
5 !== "5" // true - strict not equal (different types)

// Comparison operators
5 > 3     // true - 5 is greater than 3
5 < 3     // false - 5 is NOT less than 3
5 >= 5    // true - 5 is greater than OR equal to 5
5 <= 4    // false - 5 is NOT less than or equal to 4

Logical Operators

// Logical AND (&&) - both must be true
// Returns true only if both operands are true
true && false  // false - second is false
true && true   // true - both are true

// Logical OR (||) - at least one must be true
// Returns true if either operand is true
true || false  // true - first is true
false || false // false - both are false

// Logical NOT (!) - reverses boolean value
!true          // false - opposite of true
!false         // true - opposite of false

// Short-circuit evaluation
// && stops at first false, || stops at first true
true && console.log("This runs")   // Executes because first is true
false || console.log("This also runs") // Executes because first is false

Functions

What are Functions?

Functions are reusable blocks of code that perform a specific task. They help organize code and avoid repetition.

Function Declarations

// Function declaration syntax
// 'function' keyword - declares a function
// 'greet' - function name (can be called later)
// '(name)' - parameter (input value)
function greet(name) {
    // 'return' - sends the result back to caller
    // Concatenates strings to create greeting message
    return "Hello, " + name + "!";
}

// Calling/invoking the function
// Pass "Alice" as argument, stores result in console.log()
console.log(greet("Alice")); // Output: "Hello, Alice!"

Function Expressions

// Function expression - function stored in a variable
// 'const' - constant variable (cannot be reassigned)
// Anonymous function (no name) assigned to 'greet'
// Note: ends with semicolon (not required but good practice)
const greet = function(name) {
    return "Hello, " + name + "!";
};

// Usage is the same as function declaration
console.log(greet("Bob")); // Output: "Hello, Bob!"

Arrow Functions (ES6)

// Arrow function syntax (ES6 - modern JavaScript)
// Uses '=>' arrow operator
// 'const' - variable to store function
// '(name)' - parameter in parentheses
const greet = (name) => {
    return "Hello, " + name + "!";
};

// Shorter syntax (single expression)
// When function body is one expression, can omit {}
// Automatically returns the expression result
const greet2 = name => "Hello, " + name + "!";

// Multiple parameters - use parentheses
// Adds two numbers and returns result
const add = (a, b) => a + b;

// No parameters - empty parentheses required
// Returns a simple greeting string
const sayHi = () => "Hi!";

Default Parameters

// Default parameter - provides fallback value
// If no argument passed, uses "Guest" as default
// '=' assigns default value to parameter
function greet(name = "Guest") {
    return "Hello, " + name + "!";
}

// No argument passed - uses default value "Guest"
greet()        // Output: "Hello, Guest!"

// Argument provided - uses "John" instead of default
greet("John")  // Output: "Hello, John!"

Function Scope

// Global scope - accessible everywhere
// Declared outside any function
let globalVar = "I'm global";

// Function creates its own scope
function myFunction() {
    // Local scope - only accessible inside this function
    // 'let' creates block-scoped variable
    let localVar = "I'm local";
    
    // Functions can access global variables
    console.log(globalVar); // Output: "I'm global"
    
    // Functions can access their own local variables
    console.log(localVar);  // Output: "I'm local"
}

// Global scope cannot access function's local variables
// This will cause ReferenceError
console.log(localVar); // Error! localVar is not defined

Control Flow

If/Else Statements

// Declare variable with age value
let age = 18;

// If statement - checks condition first
// Condition: age is greater than or equal to 18
if (age >= 18) {
    // Executes if condition is true
    console.log("You are an adult");
} 
// Else if - checks another condition if first is false
else if (age >= 13) {
    // Executes if age is between 13-17
    console.log("You are a teenager");
} 
// Else - executes if all previous conditions are false
else {
    // Executes if age is less than 13
    console.log("You are a child");
}

Ternary Operator

// Initialize age variable
let age = 20;

// Ternary operator: condition ? valueIfTrue : valueIfFalse
// Shorthand for if/else statement
// Syntax: condition ? trueValue : falseValue
let status = age >= 18 ? "Adult" : "Minor";
// If age >= 18 is true → returns "Adult"
// If age >= 18 is false → returns "Minor"

// Equivalent if/else:
// if (age >= 18) {
//     status = "Adult";
// } else {
//     status = "Minor";
// }

Switch Statement

// Variable to check
let day = "Monday";

// Switch statement - evaluates value and matches cases
// Better for multiple conditions compared to if/else chains
switch(day) {
    // Case: when day equals "Monday"
    case "Monday":
        console.log("Start of work week");
        break; // Exit switch (prevents falling through to next case)
    
    // Case: when day equals "Friday"
    case "Friday":
        console.log("TGIF!");
        break;
    
    // Multiple cases with same action (no break between them)
    case "Saturday":
    case "Sunday":
        console.log("Weekend!");
        break;
    
    // Default: executes if no cases match
    default:
        console.log("Mid-week");
}

For Loop

// Traditional for loop
// Syntax: for (initialization; condition; increment)
// Initialization: let i = 0 (start at 0)
// Condition: i < 5 (continue while i is less than 5)
// Increment: i++ (increase i by 1 each iteration)
for (let i = 0; i < 5; i++) {
    console.log(i); // Output: 0, 1, 2, 3, 4
}

// For...of loop - iterates over array values
// 'fruit' gets each element from array in order
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
    console.log(fruit); // Output: "apple", then "banana", then "orange"
}

// For...in loop - iterates over object properties
// 'key' gets each property name from object
let person = {name: "John", age: 30};
for (let key in person) {
    // person[key] accesses the value of each property
    console.log(key + ": " + person[key]); 
    // Output: "name: John", then "age: 30"
}

While Loop

// While loop - checks condition before each iteration
// Initialize counter variable
let i = 0;
// Condition: continue while i is less than 5
while (i < 5) {
    console.log(i); // Output current value
    i++;            // Increment counter (prevents infinite loop)
}
// Loop continues: 0, 1, 2, 3, 4 (stops when i becomes 5)

// Do...while loop - executes code first, then checks condition
// Guarantees at least one execution
let j = 0;
do {
    console.log(j); // Executes first
    j++;            // Increment counter
} while (j < 5);    // Then checks condition
// Difference: do...while always runs at least once

Break and Continue

// Break - exit the loop
for (let i = 0; i < 10; i++) {
    if (i === 5) break;
    console.log(i); // 0, 1, 2, 3, 4
}

// Continue - skip to next iteration
for (let i = 0; i < 5; i++) {
    if (i === 2) continue;
    console.log(i); // 0, 1, 3, 4
}

Arrays

Creating Arrays

// Array literal - recommended way to create arrays
// Square brackets [] with comma-separated values
let fruits = ["apple", "banana", "orange"];
// Index:        0        1         2

// Using Array constructor - less common
// 'new' keyword creates new Array instance
let numbers = new Array(1, 2, 3);

// Empty array - useful for building arrays dynamically
let empty = [];

Accessing Array Elements

let fruits = ["apple", "banana", "orange"];

fruits[0]  // "apple" (first element)
fruits[1]  // "banana"
fruits.length  // 3 (number of elements)

Array Methods

Adding/Removing Elements

let arr = [1, 2, 3];

// Add to end
arr.push(4);        // [1, 2, 3, 4]

// Remove from end
arr.pop();          // returns 4, arr = [1, 2, 3]

// Add to beginning
arr.unshift(0);     // [0, 1, 2, 3]

// Remove from beginning
arr.shift();        // returns 0, arr = [1, 2, 3]

// Add/remove at specific index
arr.splice(1, 1, 99); // Remove 1 element at index 1, add 99
// arr = [1, 99, 3]

Finding Elements

let arr = [1, 2, 3, 4, 5];

arr.indexOf(3)      // 2 (returns index)
arr.includes(3)      // true (checks existence)
arr.find(x => x > 3) // 4 (returns first matching element)
arr.findIndex(x => x > 3) // 3 (returns index)

Transforming Arrays

let numbers = [1, 2, 3];

// map - transform each element
numbers.map(x => x * 2)  // [2, 4, 6]

// filter - keep elements that match condition
numbers.filter(x => x > 1)  // [2, 3]

// reduce - combine elements into single value
numbers.reduce((sum, x) => sum + x, 0)  // 6

// forEach - execute function for each element
numbers.forEach(x => console.log(x));

Objects

Creating Objects

// Object literal
let person = {
    name: "John",
    age: 30,
    city: "New York"
};

// Using constructor
let person2 = new Object();
person2.name = "Jane";
person2.age = 25;

Accessing Object Properties

let person = {name: "John", age: 30};

// Dot notation
person.name  // "John"
person.age   // 30

// Bracket notation
person["name"]  // "John"
person["age"]   // 30

let key = "name";
person[key]  // "John" (useful for dynamic keys)

Adding and Modifying Properties

let person = {name: "John"};

// Add property
person.age = 30;
person["city"] = "New York";

// Modify property
person.name = "Jane";

// Delete property
delete person.city;

Object Methods

let person = {
    name: "John",
    age: 30,
    greet: function() {
        return "Hello, I'm " + this.name;
    },
    // ES6 method shorthand
    introduce() {
        return `Hi, I'm ${this.name} and I'm ${this.age}`;
    }
};

person.greet();  // "Hello, I'm John"

Iterating Over Objects

let person = {name: "John", age: 30, city: "NYC"};

// For...in loop
for (let key in person) {
    console.log(key + ": " + person[key]);
}

// Object.keys()
Object.keys(person)  // ["name", "age", "city"]

// Object.values()
Object.values(person)  // ["John", 30, "NYC"]

// Object.entries()
Object.entries(person)  // [["name", "John"], ["age", 30], ...]

DOM Manipulation

What is the DOM?

The Document Object Model (DOM) is a programming interface for HTML. It represents the page structure, allowing JavaScript to manipulate the content and structure.

Selecting Elements

// By ID
let element = document.getElementById("myId");

// By class name (returns array-like)
let elements = document.getElementsByClassName("myClass");

// By tag name (returns array-like)
let divs = document.getElementsByTagName("div");

// Query selector (CSS selector syntax)
let element = document.querySelector("#myId");
let elements = document.querySelectorAll(".myClass");

Modifying Content

let element = document.getElementById("myElement");

// Text content
element.textContent = "New text";
element.innerText = "New text";

// HTML content
element.innerHTML = "<strong>Bold text</strong>";

// Attributes
element.setAttribute("class", "newClass");
element.className = "newClass";
element.id = "newId";

Styling Elements

let element = document.getElementById("myElement");

element.style.color = "red";
element.style.backgroundColor = "blue";
element.style.fontSize = "20px";
element.style.display = "none";

Creating and Adding Elements

// Create element
let newDiv = document.createElement("div");
newDiv.textContent = "Hello!";
newDiv.className = "my-div";

// Append to parent
let parent = document.getElementById("container");
parent.appendChild(newDiv);

// Insert before
let sibling = document.getElementById("sibling");
parent.insertBefore(newDiv, sibling);

// Remove element
parent.removeChild(newDiv);

Event Listeners

let button = document.getElementById("myButton");

// Add event listener
button.addEventListener("click", function() {
    console.log("Button clicked!");
});

// Arrow function
button.addEventListener("click", () => {
    console.log("Clicked!");
});

// Common events: click, change, input, submit, mouseover, keydown

Code Playground

Practice your JavaScript code here! Write code in the editor and see the output.

JavaScript Editor
1
Output

JavaScript Cheat Sheet

Variables & Constants

let variable = value;
const constant = value;
var oldWay = value;

Data Types

typeof value              // Check type
"string", 'string'       // String
42, 3.14                 // Number
true, false              // Boolean
null                     // Null
undefined                // Undefined
{key: value}              // Object
[1, 2, 3]                // Array

Operators

+ - * / % **             // Arithmetic
+= -= *= /= %=           // Assignment
== === != !==            // Comparison
&& || !                  // Logical
?:                       // Ternary

Functions

function name() {}       // Declaration
const fn = function() {} // Expression
const fn = () => {}      // Arrow
fn(param = default)      // Default param

Control Flow

if (condition) {}         // If statement
else if (condition) {}   // Else if
else {}                  // Else
condition ? a : b        // Ternary
switch(value) {          // Switch
    case x: break;
    default: break;
}

Loops

for (let i=0; i<n; i++) {} // For loop
for (let item of arr) {}  // For...of
for (let key in obj) {}   // For...in
while (condition) {}      // While
do {} while (condition)   // Do...while
break                     // Exit loop
continue                  // Skip iteration

Arrays

arr.push(item)           // Add to end
arr.pop()                // Remove from end
arr.unshift(item)        // Add to start
arr.shift()              // Remove from start
arr.length               // Get length
arr.indexOf(item)         // Find index
arr.includes(item)       // Check existence
arr.map(fn)              // Transform
arr.filter(fn)           // Filter
arr.reduce(fn)           // Reduce
arr.forEach(fn)           // Iterate

Objects

obj.property             // Dot notation
obj["property"]          // Bracket notation
Object.keys(obj)         // Get keys
Object.values(obj)       // Get values
Object.entries(obj)      // Get entries
delete obj.property      // Delete property

DOM

document.getElementById(id)
document.querySelector(selector)
element.textContent
element.innerHTML
element.style.property
element.addEventListener(event, fn)

String Methods

str.length               // Length
str.toUpperCase()        // Upper case
str.toLowerCase()        // Lower case
str.trim()               // Trim whitespace
str.split(delimiter)     // Split to array
str.includes(substr)     // Check substring
str.indexOf(substr)      // Find index
str.substring(start, end) // Substring

Useful Methods

JSON.parse(json)         // Parse JSON
JSON.stringify(obj)      // Stringify
parseInt(str)            // Parse integer
parseFloat(str)          // Parse float
Math.random()            // Random 0-1
Math.floor(n)            // Round down
Math.max(a, b)           // Maximum
Math.min(a, b)           // Minimum

External Resources

Here are some excellent external resources to help you learn JavaScript: