Interactive JavaScript Book

Variables & Data Types

The basic building blocks of any JavaScript program.

Understanding Variables (var, let, const)

Variables are containers for storing data. Use let for variables that will change, and const for variables that won't. var is the older, function-scoped way.

// 'let' for variables that can change
let age = 30;
age = 31;

// 'const' for constant variables
const birthYear = 1995;
// birthYear = 1996; // This would cause an error!

// 'var' is the old way (generally avoid)
var oldWay = "Avoid this";
Common Data Types

JavaScript has "primitive" types (like strings, numbers, booleans) and "complex" types (like objects and arrays).

let x_str = "Hello";     // String
let x_num = 20.5;        // Number
let x_bool = true;       // Boolean
let x_obj = {name: "John"}; // Object
let x_arr = ["a", "b"];  // Array
let x_null = null;       // null (intentional absence)
let x_undef;              // undefined (unassigned)

Control Flow

How to make decisions and repeat actions in your code.

Conditionals (if, else if, else)

Conditionals allow your program to execute certain blocks of code only if a condition is met.

let temperature = 25;

if (temperature > 30) {
    console.log("It's a hot day!");
} else if (temperature > 20) {
    console.log("It's a pleasant day.");
} else {
    console.log("It's cold.");
}
For Loops

A for loop is used for iterating a specific number of times. The for...of loop is used for iterating over arrays.

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

// Modern 'for...of' loop for arrays
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
    console.log(fruit);
}
While Loops

A while loop executes a set of statements as long as a condition is true.

let count = 0;
while (count < 5) {
    console.log(count);
    count++;  // Don't forget to increment!
}

Functions

Reusable blocks of code that perform a specific task.

Defining Functions

Functions can be defined as a "declaration" or an "expression".

// Function Declaration
function greet() {
    console.log("Hello, world!");
}
greet(); // Call the function

// Function Expression
const greet2 = function() {
    console.log("Hello again!");
};
greet2();
Arrow Functions (ES6)

Arrow functions are a modern, concise way to write functions. They are very common in modern JavaScript.

// A simple arrow function
const add = (a, b) => {
    return a + b;
};

// Implicit return for one-line functions
const subtract = (a, b) => a - b;

console.log(add(5, 10));     // Output: 15
console.log(subtract(10, 3)); // Output: 7

Arrays & Objects

The two most important data structures in JavaScript.

Arrays

Arrays are ordered lists of values. They can hold items of any type and have many useful built-in methods.

const colors = ["red", "green", "blue"];
colors.push("yellow"); // Add to end
console.log(colors[1]); // Output: green

// Loop with .forEach()
colors.forEach((color) => {
    console.log(color);
});
Objects

Objects are collections of key:value pairs. This is how you represent complex data, like a user.

const person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    greet: function() {
        console.log(`Hello, my name is ${this.firstName}`);
    }
};

console.log(person.age); // Output: 30
person.greet(); // Output: Hello, my name is John

Object-Oriented Programming

A paradigm based on "objects" and "classes".

Classes (ES6)

A class is a blueprint for creating objects. The constructor method is called when a new object is created.

class Dog {
    // The "constructor" method
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // A method
    bark() {
        console.log(`Woof! My name is ${this.name}`);
    }
}

// Create an 'object' (instance)
const myDog = new Dog("Buddy", 3);
console.log(myDog.name); // Output: Buddy
myDog.bark(); // Output: Woof! My name is Buddy
Inheritance

Inheritance allows a new class (child) to "extend" an existing class (parent), inheriting its properties and methods.

// Parent class
class Animal {
    constructor(name) {
        this.name = name;
    }
    
    speak() {
        console.log(`${this.name} makes a noise.`);
    }
}

// Child class (inherits from Animal)
class Cat extends Animal {
    speak() {
        console.log(`${this.name} says Meow.`);
    }
}

const fluffy = new Cat("Fluffy");
fluffy.speak(); // Output: Fluffy says Meow.

Advanced Concepts

Topics for interacting with browsers and servers.

DOM Manipulation

The Document Object Model (DOM) is how JavaScript interacts with HTML. You can select elements, change their content, and listen for events.

// --- Assume this HTML exists: ---
// <h1 id="title">Old Title</h1>
// <button id="myButton">Click Me</button>

// --- In your JS file: ---
// Get an element by its ID
const titleElement = document.getElementById('title');
titleElement.textContent = 'New Title!'; // Change text

// Add an event listener
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
    alert('Button was clicked!');
});
Async/Await (fetch)

async/await is modern syntax for handling asynchronous operations (like fetching data from an API) in a clean, readable way.

// 'async' marks the function as asynchronous
async function fetchData() {
  try {
    // 'await' pauses execution until the data returns
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    
    console.log(data);
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
}

fetchData();