Learn JavaScript Step by Step Tutorial with Real Examples
A complete beginner roadmap to JavaScript. Covers variables, data types, operators, conditionals, loops, functions, arrays, objects, DOM basics, and a real-world project walkthrough with step-by-step code examples.
JavaScript is the programming language of the web. Every modern browser runs it, every interactive website depends on it, and it powers both frontend and backend development. If you are starting from zero, this tutorial walks you through JavaScript fundamentals in logical order, with real code examples you can run immediately.
Each section builds on the previous one. By the end, you will understand variables, data types, operators, conditionals, loops, functions, arrays, and objects well enough to build a complete working project.
Step 1: Variables and Data Types
Variables store values so you can use them later. JavaScript provides three ways to declare variables: const, let, and var. Modern JavaScript favors const and let.
// const: value cannot be reassigned
const appName = "TaskManager";
// let: value can be reassigned
let taskCount = 0;
taskCount = 5; // Allowed
// var: older syntax, function-scoped (avoid in new code)
var legacyVar = "old style";JavaScript has several data types:
| Type | Example | Description |
|---|---|---|
| String | "Hello" | Text wrapped in quotes |
| Number | 42, 3.14 | Integers and decimals |
| Boolean | true, false | Logical values |
| Null | null | Intentionally empty |
| Undefined | undefined | Declared but not assigned |
| Object | { name: "Alice" } | Key-value collections |
| Array | [1, 2, 3] | Ordered lists |
const userName = "Alice"; // String
const userAge = 28; // Number
const isActive = true; // Boolean
const middleName = null; // Null
let nickname; // Undefined (declared, no value)
console.log(typeof userName); // "string"
console.log(typeof userAge); // "number"
console.log(typeof isActive); // "boolean"Step 2: Operators
Operators let you perform calculations, compare values, and combine conditions.
// Arithmetic
const total = 10 + 5; // 15
const remainder = 10 % 3; // 1
const power = 2 ** 8; // 256
// Comparison (always use ===)
console.log(5 === 5); // true
console.log(5 === "5"); // false (different types)
console.log(10 > 5); // true
// Logical
const hasAccess = true && true; // true (AND)
const eitherOne = false || true; // true (OR)
const flipped = !true; // false (NOT)Template Literals
Template literals use backticks for string interpolation:
const name = "Alice";
const age = 28;
// Old way: concatenation
const greetOld = "Hello, " + name + "! You are " + age + " years old.";
// Modern way: template literal
const greetNew = `Hello, ${name}! You are ${age} years old.`;
console.log(greetNew);
// "Hello, Alice! You are 28 years old."Step 3: Conditionals
Conditional statements let your code make decisions:
const hour = 14;
if (hour < 12) {
console.log("Good morning");
} else if (hour < 18) {
console.log("Good afternoon");
} else {
console.log("Good evening");
}
// "Good afternoon"For simple conditions, the ternary operator offers a compact syntax:
const age = 20;
const canVote = age >= 18 ? "Yes" : "No";
console.log(`Can vote: ${canVote}`); // "Can vote: Yes"When comparing one value against many options, use a switch statement:
const role = "editor";
switch (role) {
case "admin":
console.log("Full access");
break;
case "editor":
console.log("Can edit content");
break;
case "viewer":
console.log("Read only");
break;
default:
console.log("Unknown role");
}
// "Can edit content"Step 4: Loops
Loops repeat code until a condition is met. The for loop is the most common:
// Print numbers 1 through 5
for (let i = 1; i <= 5; i++) {
console.log(`Number: ${i}`);
}
// Loop through an array
const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}The while loop runs while a condition is true:
let countdown = 5;
while (countdown > 0) {
console.log(`T-minus ${countdown}`);
countdown--;
}
console.log("Liftoff!");The for...of loop is the cleanest way to iterate over array values:
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// cherryStep 5: Functions
Functions let you organize code into reusable blocks:
// Function declaration
function calculateTip(bill, percentage) {
return bill * (percentage / 100);
}
console.log(calculateTip(50, 20)); // 10
// Arrow function
const greet = (name) => `Hello, ${name}!`;
console.log(greet("Bob")); // "Hello, Bob!"Functions can have default parameters:
function createUser(name, role = "viewer") {
return { name, role };
}
console.log(createUser("Alice")); // { name: "Alice", role: "viewer" }
console.log(createUser("Bob", "admin")); // { name: "Bob", role: "admin" }Callback Functions
A callback is a function passed to another function:
function processItems(items, processor) {
const results = [];
for (const item of items) {
results.push(processor(item));
}
return results;
}
const numbers = [1, 2, 3, 4, 5];
const doubled = processItems(numbers, (n) => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]Step 6: Arrays
Arrays are ordered collections of values:
const tasks = ["Buy groceries", "Clean house", "Walk dog"];
// Access by index (zero-based)
console.log(tasks[0]); // "Buy groceries"
console.log(tasks[2]); // "Walk dog"
// Add to the end
tasks.push("Cook dinner");
// Remove from the end
const lastTask = tasks.pop(); // "Cook dinner"
// Get array length
console.log(tasks.length); // 3Essential Array Methods
const prices = [29.99, 9.99, 49.99, 14.99, 79.99];
// map: transform every element
const withTax = prices.map((price) => price * 1.1);
console.log(withTax); // [32.989, 10.989, 54.989, 16.489, 87.989]
// filter: keep elements that pass a test
const expensive = prices.filter((price) => price > 20);
console.log(expensive); // [29.99, 49.99, 79.99]
// reduce: accumulate into a single value
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 184.95
// find: get the first match
const firstCheap = prices.find((price) => price < 15);
console.log(firstCheap); // 9.99| Method | Returns | Purpose |
|---|---|---|
map() | New array (same length) | Transform each element |
filter() | New array (subset) | Keep elements matching a condition |
reduce() | Single value | Accumulate all elements into one result |
find() | Single element or undefined | First element matching a condition |
forEach() | undefined | Run a side effect for each element |
sort() | Mutated original array | Sort elements in place |
Step 7: Objects
Objects store data as key-value pairs. They are perfect for representing real-world entities:
const user = {
name: "Alice",
age: 28,
email: "alice@example.com",
isActive: true,
skills: ["JavaScript", "Python", "SQL"]
};
// Access properties
console.log(user.name); // "Alice"
console.log(user["email"]); // "alice@example.com"
// Modify a property
user.age = 29;
// Add a new property
user.role = "developer";
// Delete a property
delete user.isActive;
console.log(user);Object Methods
Objects can contain functions (called methods):
const calculator = {
history: [],
add(a, b) {
const result = a + b;
this.history.push(`${a} + ${b} = ${result}`);
return result;
},
subtract(a, b) {
const result = a - b;
this.history.push(`${a} - ${b} = ${result}`);
return result;
},
getHistory() {
return this.history;
}
};
calculator.add(5, 3); // 8
calculator.subtract(10, 4); // 6
console.log(calculator.getHistory());
// ["5 + 3 = 8", "10 - 4 = 6"]Step 8: Building a Real Project
Let us combine everything into a working task manager:
// Task Manager Application
const taskManager = {
tasks: [],
nextId: 1,
addTask(title, priority = "medium") {
const task = {
id: this.nextId++,
title,
priority,
completed: false,
createdAt: new Date().toISOString()
};
this.tasks.push(task);
return task;
},
completeTask(id) {
const task = this.tasks.find((t) => t.id === id);
if (!task) {
return { error: "Task not found" };
}
task.completed = true;
return task;
},
removeTask(id) {
const index = this.tasks.findIndex((t) => t.id === id);
if (index === -1) {
return { error: "Task not found" };
}
return this.tasks.splice(index, 1)[0];
},
getTasksByPriority(priority) {
return this.tasks.filter((t) => t.priority === priority);
},
getPendingTasks() {
return this.tasks.filter((t) => !t.completed);
},
getSummary() {
const total = this.tasks.length;
const completed = this.tasks.filter((t) => t.completed).length;
const pending = total - completed;
const byPriority = this.tasks.reduce((acc, task) => {
acc[task.priority] = (acc[task.priority] || 0) + 1;
return acc;
}, {});
return { total, completed, pending, byPriority };
}
};
// Use the task manager
taskManager.addTask("Set up project structure", "high");
taskManager.addTask("Write unit tests", "high");
taskManager.addTask("Add documentation", "medium");
taskManager.addTask("Fix typos in README", "low");
taskManager.addTask("Deploy to production", "high");
// Complete some tasks
taskManager.completeTask(1);
taskManager.completeTask(3);
// Get summary
console.log(taskManager.getSummary());
// { total: 5, completed: 2, pending: 3, byPriority: { high: 3, medium: 1, low: 1 } }
// Get pending high-priority tasks
const urgentPending = taskManager.getPendingTasks()
.filter((t) => t.priority === "high");
console.log(urgentPending.map((t) => t.title));
// ["Write unit tests", "Deploy to production"]This project uses every concept from the tutorial: variables, objects, arrays, functions, conditionals, loops (inside filter, find, reduce), and template literals.
What to Learn Next
Now that you have the fundamentals, here are the next topics to explore:
- Array destructuring for cleaner variable extraction
- Higher-order functions for powerful functional patterns
- Scope and hoisting for understanding variable behavior
- The DOM for building interactive web pages
- Objects in depth for mastering JavaScript's core data structure
Rune AI
Key Insights
- Start with const and let: use
constby default,letwhen reassignment is needed, and avoidvarin new code. - Functions are the core building block: organize your code into small, focused functions with descriptive names and default parameters.
- Arrays and objects work together: arrays hold ordered collections, objects hold named properties, and combining them models real-world data effectively.
- Build projects early: reading tutorials is a starting point, but writing actual code (like the task manager) cements your understanding.
- Learn concepts in order: variables, operators, conditionals, loops, functions, arrays, objects, then advance to closures, prototypes, and async programming.
Frequently Asked Questions
Do I need to learn HTML and CSS before JavaScript?
How long does it take to learn JavaScript basics?
Should I use const, let, or var?
What is the best way to practice JavaScript?
What is the difference between JavaScript and TypeScript?
Conclusion
JavaScript is a practical, versatile language that you can start using immediately. By learning variables, operators, conditionals, loops, functions, arrays, and objects in order, each concept builds naturally on the previous one. The task manager project demonstrates how all these pieces fit together in real code. Focus on building small projects to reinforce what you learn, and gradually move into advanced topics like closures, prototypes, and asynchronous programming as you grow more confident.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.