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.

JavaScriptbeginner
20 min read

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.

javascriptjavascript
// 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:

TypeExampleDescription
String"Hello"Text wrapped in quotes
Number42, 3.14Integers and decimals
Booleantrue, falseLogical values
NullnullIntentionally empty
UndefinedundefinedDeclared but not assigned
Object{ name: "Alice" }Key-value collections
Array[1, 2, 3]Ordered lists
javascriptjavascript
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.

javascriptjavascript
// 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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
// 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:

javascriptjavascript
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:

javascriptjavascript
const fruits = ["apple", "banana", "cherry"];
 
for (const fruit of fruits) {
  console.log(fruit);
}
// apple
// banana
// cherry

Step 5: Functions

Functions let you organize code into reusable blocks:

javascriptjavascript
// 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:

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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); // 3

Essential Array Methods

javascriptjavascript
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
MethodReturnsPurpose
map()New array (same length)Transform each element
filter()New array (subset)Keep elements matching a condition
reduce()Single valueAccumulate all elements into one result
find()Single element or undefinedFirst element matching a condition
forEach()undefinedRun a side effect for each element
sort()Mutated original arraySort elements in place

Step 7: Objects

Objects store data as key-value pairs. They are perfect for representing real-world entities:

javascriptjavascript
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):

javascriptjavascript
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:

javascriptjavascript
// 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:

  1. Array destructuring for cleaner variable extraction
  2. Higher-order functions for powerful functional patterns
  3. Scope and hoisting for understanding variable behavior
  4. The DOM for building interactive web pages
  5. Objects in depth for mastering JavaScript's core data structure
Rune AI

Rune AI

Key Insights

  • Start with const and let: use const by default, let when reassignment is needed, and avoid var in 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.
RunePowered by Rune AI

Frequently Asked Questions

Do I need to learn HTML and CSS before JavaScript?

HTML and CSS are helpful for building web pages, but they are not required to start learning JavaScript. You can practice JavaScript in a browser console or Node.js environment without any HTML knowledge. When you are ready to build interactive web pages, learning HTML structure and CSS styling will become essential. Many developers learn all three simultaneously.

How long does it take to learn JavaScript basics?

With consistent daily practice (1 to 2 hours), most beginners can understand variables, conditionals, loops, and functions within 2 to 4 weeks. Becoming comfortable with arrays, objects, and callbacks typically takes another 2 to 4 weeks. Building real projects is where the learning accelerates, so start coding small projects as early as possible rather than only reading tutorials.

Should I use const, let, or var?

Use `const` by default for any value that will not be reassigned. Use `let` when you need to change the value later (like loop counters or accumulators). Avoid `var` in new code because its function-scoping and hoisting behavior cause subtle bugs that `const` and `let` eliminate with block scoping.

What is the best way to practice JavaScript?

Start by modifying the code examples in tutorials. Then build small projects: a calculator, a to-do list, a quiz app, or a unit converter. Each project forces you to combine multiple concepts. Coding challenges on platforms like LeetCode or Codewars help you practice algorithms, but real projects develop practical skills faster.

What is the difference between JavaScript and TypeScript?

TypeScript is a superset of JavaScript that adds static type checking. Every valid JavaScript program is also valid TypeScript, but TypeScript catches type errors before your code runs. Most large-scale JavaScript projects use TypeScript for better tooling, autocompletion, and fewer runtime bugs. Learn JavaScript first, then adopt TypeScript once you are comfortable with the fundamentals.

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.