🛠 Tool HTML CSS JS About Contact

Learn JavaScript – Free Complete Tutorial

Master JavaScript from scratch. Learn variables, functions, DOM manipulation, events, arrays, loops and modern ES6+ features.

🆓 Free 👶 Beginner Friendly ⚡ Live Examples 🔥 ES6+ Modern JS
1

What is JavaScript?

JavaScript is the programming language of the web. It makes pages interactive — responding to clicks, validating forms, fetching data, animating elements, and much more.

JavaScript runs directly in the browser. You don't need to install anything — just open your browser and start coding.

JavaScript is different from Java — they are completely unrelated languages. JavaScript was created by Brendan Eich in 1995 and runs in every modern browser.
JavaScript
// Your first JavaScript program
console.log("Hello, World!");

// Show alert in browser
alert("Welcome to JavaScript!");

// Add JS to HTML with script tag
// <script src="app.js"></script>
// <script> ... inline ... </script>
Try in Editor
2

Variables

Variables store data values. Modern JavaScript uses let and const. Avoid var in new code.

JavaScript
// const: cannot be reassigned (use by default)
const name = "Alice";
const age = 28;
const PI = 3.14159;

// let: can be reassigned
let score = 0;
score = 100;   // OK

// var: old style, avoid in modern JS
var oldStyle = "avoid this";

// Template literals (string with variables)
const greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting);
// Output: Hello, Alice! You are 28 years old.
Try in Editor
3

Data Types

JavaScript has several built-in data types. Use typeof to check the type of a value.

JavaScript
// String
const text = "Hello";

// Number (integers and floats)
const count = 42;
const price = 9.99;

// Boolean
const isLoggedIn = true;

// null (intentional empty value)
const empty = null;

// undefined (declared but not assigned)
let notSet;
console.log(notSet); // undefined

// Array
const colors = ["red", "green", "blue"];

// Object
const user = { name: "Alice", age: 28 };

// Check type with typeof
typeof text;       // "string"
typeof count;      // "number"
typeof isLoggedIn; // "boolean"
typeof colors;     // "object"
Try in Editor
4

Operators

Operators perform operations on values — arithmetic, comparison, logical, and more.

JavaScript
// Arithmetic
10 + 5   // 15 (add)
10 - 3   // 7  (subtract)
4  * 3   // 12 (multiply)
10 / 2   // 5  (divide)
10 % 3   // 1  (remainder)
2  ** 8  // 256 (power)

// Comparison (always use === not ==)
5 === 5   // true (strict equal)
5 !== 3   // true (not equal)
5 > 3    // true
5 >= 5   // true

// Logical
true && false  // false (AND)
true || false  // true  (OR)
!true          // false (NOT)

// Nullish coalescing (??) – default if null/undefined
const val = null ?? "default";  // "default"

// Optional chaining (?.) – safe property access
const city = user?.address?.city; // undefined (no error)
Try in Editor
5

Conditionals

Conditionals execute different code based on conditions.

JavaScript
const score = 75;

// if / else if / else
if (score >= 90) {
  console.log("A");
} else if (score >= 70) {
  console.log("B");
} else {
  console.log("C");
}

// Ternary operator (short if/else)
const pass = score >= 60 ? "Pass" : "Fail";

// Switch
const day = "Monday";
switch (day) {
  case "Monday":
    console.log("Start of the week");
    break;
  case "Friday":
    console.log("Almost weekend!");
    break;
  default:
    console.log("Midweek");
}
Try in Editor
6

Loops

Loops repeat code multiple times. JavaScript has several loop types for different situations.

JavaScript
// for loop
for (let i = 0; i < 5; i++) {
  console.log(i); // 0, 1, 2, 3, 4
}

// while loop
let count = 0;
while (count < 3) {
  console.log(count);
  count++;
}

// for...of (iterate array items) – most common
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
  console.log(fruit);
}

// forEach (array method with callback)
fruits.forEach((fruit, index) => {
  console.log(`${index}: ${fruit}`);
});

// for...in (iterate object keys)
const user = { name: "Alice", age: 28 };
for (const key in user) {
  console.log(`${key}: ${user[key]}`);
}
Try in Editor
7

Functions

Functions are reusable blocks of code. They take inputs (parameters) and return outputs.

JavaScript
// Function declaration
function greet(name) {
  return `Hello, ${name}!`;
}
console.log(greet("Bob")); // Hello, Bob!

// Default parameter
function add(a, b = 0) {
  return a + b;
}
add(5);     // 5
add(5, 3); // 8

// Arrow function (ES6 – modern, concise)
const multiply = (a, b) => a * b;
multiply(4, 3); // 12

// Arrow function with body block
const square = (n) => {
  const result = n * n;
  return result;
};

// Rest parameters (...args)
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
Try in Editor
8

Arrays

Arrays store ordered lists of values. JavaScript arrays have many powerful built-in methods.

JavaScript
const nums = [1, 2, 3, 4, 5];

// Access items (0-indexed)
nums[0];     // 1 (first)
nums.at(-1); // 5 (last)
nums.length;  // 5

// Add / Remove
nums.push(6);     // add to end → [1,2,3,4,5,6]
nums.pop();       // remove from end
nums.unshift(0); // add to start
nums.shift();     // remove from start

// Transform & filter
nums.map(n => n * 2);        // [2,4,6,8,10]
nums.filter(n => n > 2);     // [3,4,5]
nums.find(n => n > 3);       // 4 (first match)
nums.reduce((a, b) => a + b); // 15 (sum)

// Search
nums.includes(3);  // true
nums.indexOf(4);   // 3

// Combine arrays with spread
const more = [...nums, 6, 7];
Try in Editor
9

Objects

Objects store data as key-value pairs and can also contain methods (functions as values).

JavaScript
// Object literal
const person = {
  name: "Alice",
  age: 28,
  isActive: true,
  greet() {
    return `Hi, I'm ${this.name}`;
  }
};

// Access properties
person.name;        // "Alice"
person["age"];      // 28
person.greet();     // "Hi, I'm Alice"

// Destructuring (unpack to variables)
const { name, age } = person;

// Spread (copy + override)
const updated = { ...person, age: 29 };

// Computed property name
const key = "color";
const obj = { [key]: "blue" }; // { color: "blue" }

// Object utility methods
Object.keys(person);    // ["name","age","isActive","greet"]
Object.values(person);  // ["Alice", 28, true, fn]
Object.entries(person); // [["name","Alice"], ...]
Try in Editor
10

DOM Manipulation

The DOM (Document Object Model) is the browser's live representation of the HTML page. JavaScript can read and change it dynamically.

JavaScript
// Select elements
const el  = document.getElementById("myId");
const el  = document.querySelector(".myClass");   // first match
const all = document.querySelectorAll("p");        // NodeList of all <p>

// Read & change content
el.textContent = "New text";
el.innerHTML   = "<strong>Bold</strong>";

// Change CSS
el.style.color      = "red";
el.style.display    = "none";
el.classList.add("active");
el.classList.remove("hidden");
el.classList.toggle("open");

// Read & set attributes
el.getAttribute("href");
el.setAttribute("href", "https://example.com");

// Create & insert elements
const newP = document.createElement("p");
newP.textContent = "I was created by JS!";
document.body.appendChild(newP);

// Remove an element
el.remove();
Try in Editor
11

Events

Events allow JavaScript to react to user actions — clicks, typing, hovering, submitting forms, and more.

JavaScript
// addEventListener (recommended way)
const btn = document.querySelector("#myBtn");

btn.addEventListener("click", () => {
  alert("Button clicked!");
});

// Access event data
btn.addEventListener("click", (event) => {
  console.log(event.target);   // the clicked element
  event.preventDefault();      // stop default behavior
});

// Common event types
el.addEventListener("click",       handler); // mouse click
el.addEventListener("dblclick",    handler); // double click
el.addEventListener("mouseover",  handler); // hover
el.addEventListener("keydown",    handler); // key pressed
el.addEventListener("input",      handler); // input changed
el.addEventListener("submit",     handler); // form submit
window.addEventListener("scroll",  handler); // page scroll
window.addEventListener("load",    handler); // page loaded

// Remove event listener
el.removeEventListener("click", handler);
Try in Editor
12

ES6+ Modern JavaScript

ES6 (2015) and newer versions introduced powerful features that make JavaScript cleaner and more expressive. These are now standard in all modern browsers.

JavaScript
// Destructuring (arrays)
const [first, second, ...rest] = [1, 2, 3, 4];
// first=1, second=2, rest=[3,4]

// Spread operator
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b]; // [1,2,3,4]

// Modules (import/export)
// math.js:
export const add = (a, b) => a + b;
// main.js:
import { add } from "./math.js";

// Promises (async operations)
fetch("https://api.example.com/data")
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

// async / await (cleaner way to handle promises)
async function loadData() {
  try {
    const res  = await fetch("https://api.example.com/data");
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

// Class syntax
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound.`;
  }
}
class Dog extends Animal {
  speak() { return `${this.name} barks!`; }
}
const dog = new Dog("Rex");
dog.speak(); // "Rex barks!"
🎉 You've learned HTML, CSS & JavaScript!
Now practice in our free online editor — paste code and see it run instantly.
Open Editor