Complete JavaScript Course

Master the Language of the Web

1. Introduction to JavaScript

JavaScript is a high-level, interpreted programming language that makes web pages interactive. It's the programming language of the web, running in browsers and servers (Node.js).

What can JavaScript do?

Adding JavaScript to HTML

Try it yourself:

Click a button to see JavaScript in action!
💡 Tip: JavaScript is case-sensitive. myVariable and myvariable are different variables.

2. JavaScript Basics

Variables and Data Types

// Variable declarations let name = "John"; // String const age = 25; // Number (constant) var isStudent = true; // Boolean (avoid var, use let/const) // Data types let text = "Hello World"; // String let number = 42; // Number let decimal = 3.14; // Number (no separate float type) let isTrue = true; // Boolean let nothing = null; // Null let undefined_var; // Undefined let symbol = Symbol('id'); // Symbol (ES6) let bigInt = 123n; // BigInt (ES2020) // Objects let person = { name: "Alice", age: 30 }; // Arrays let colors = ["red", "green", "blue"];

Operators

// Arithmetic operators let a = 10, b = 3; console.log(a + b); // 13 (addition) console.log(a - b); // 7 (subtraction) console.log(a * b); // 30 (multiplication) console.log(a / b); // 3.333... (division) console.log(a % b); // 1 (modulus/remainder) console.log(a ** b); // 1000 (exponentiation) // Assignment operators let x = 5; x += 3; // x = x + 3 (8) x -= 2; // x = x - 2 (6) x *= 2; // x = x * 2 (12) x /= 3; // x = x / 3 (4) // Comparison operators console.log(5 == "5"); // true (loose equality) console.log(5 === "5"); // false (strict equality) console.log(5 != "5"); // false console.log(5 !== "5"); // true console.log(5 > 3); // true console.log(5 <= 5); // true // Logical operators console.log(true && false); // false (AND) console.log(true || false); // true (OR) console.log(!true); // false (NOT)

Control Structures

// If statements let score = 85; if (score >= 90) { console.log("A grade"); } else if (score >= 80) { console.log("B grade"); } else if (score >= 70) { console.log("C grade"); } else { console.log("Need improvement"); } // Switch statement let day = "Monday"; switch (day) { case "Monday": console.log("Start of work week"); break; case "Friday": console.log("TGIF!"); break; case "Saturday": case "Sunday": console.log("Weekend!"); break; default: console.log("Regular day"); } // Ternary operator let message = age >= 18 ? "Adult" : "Minor";

Loops

// For loop for (let i = 0; i < 5; i++) { console.log("Count: " + i); } // While loop let count = 0; while (count < 3) { console.log("While count: " + count); count++; } // Do-while loop let num = 0; do { console.log("Do-while: " + num); num++; } while (num < 2); // For...of loop (arrays) let fruits = ["apple", "banana", "orange"]; for (let fruit of fruits) { console.log(fruit); } // For...in loop (objects) let person = {name: "John", age: 30, city: "New York"}; for (let key in person) { console.log(key + ": " + person[key]); }

🏋️ Exercise 1:

Create a program that checks if a number is even or odd, and prints numbers from 1 to 10 with their even/odd status.

3. Functions

Function Declaration and Expression

// Function declaration function greet(name) { return "Hello, " + name + "!"; } // Function expression const greetExpression = function(name) { return "Hi, " + name + "!"; }; // Arrow function (ES6) const greetArrow = (name) => { return "Hey, " + name + "!"; }; // Short arrow function const greetShort = name => "Hello, " + name + "!"; // Calling functions console.log(greet("Alice")); // Hello, Alice! console.log(greetExpression("Bob")); // Hi, Bob! console.log(greetArrow("Charlie")); // Hey, Charlie! console.log(greetShort("David")); // Hello, David!

Function Demo:

Click to see function examples

4. Objects and Classes

Object Basics

// Object literal let person = { name: "John", age: 30, city: "New York", // Method greet: function() { return "Hello, I'm " + this.name; }, // ES6 method shorthand introduce() { return `I'm ${this.name}, ${this.age} years old`; } }; // Accessing properties console.log(person.name); // Dot notation console.log(person["age"]); // Bracket notation // Adding properties person.email = "john@example.com"; person["phone"] = "123-456-7890"; // Calling methods console.log(person.greet()); console.log(person.introduce());

ES6 Classes

class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { return `Hello, I'm ${this.name}`; } static species() { return "Homo sapiens"; } } class Student extends Person { constructor(name, age, grade) { super(name, age); this.grade = grade; } study() { return `${this.name} is studying`; } } // Creating instances let person1 = new Person("Alice", 25); let student1 = new Student("Bob", 20, "A"); console.log(person1.greet()); console.log(student1.study()); console.log(Person.species());

5. Arrays and Methods

Array Methods

let numbers = [1, 2, 3, 4, 5]; // forEach - execute function for each element numbers.forEach((num, index) => { console.log(`Index ${index}: ${num}`); }); // map - create new array with transformed elements let doubled = numbers.map(num => num * 2); console.log(doubled); // [2, 4, 6, 8, 10] // filter - create new array with elements that pass test let evens = numbers.filter(num => num % 2 === 0); console.log(evens); // [2, 4] // reduce - reduce array to single value let sum = numbers.reduce((total, num) => total + num, 0); console.log(sum); // 15 // find - find first element that passes test let found = numbers.find(num => num > 3); console.log(found); // 4

Array Methods Demo:

Click to see array method examples

6. DOM Manipulation

Selecting Elements

// Select by ID let element = document.getElementById("myId"); // Query selector (CSS selectors) let firstDiv = document.querySelector("div"); let allDivs = document.querySelectorAll("div"); let specificElement = document.querySelector("#myId .myClass");

Modifying Elements

let element = document.querySelector("#myElement"); // Change content element.textContent = "New text content"; element.innerHTML = "Bold text"; // Change style element.style.color = "red"; element.style.backgroundColor = "yellow"; // Add/remove classes element.classList.add("newClass"); element.classList.remove("oldClass"); element.classList.toggle("active");

7. Event Handling

Adding Event Listeners

// Click event button.addEventListener('click', function() { console.log('Button clicked!'); }); // Arrow function button.addEventListener('click', () => { console.log('Button clicked with arrow function!'); }); // Multiple events input.addEventListener('focus', handleFocus); input.addEventListener('blur', handleBlur); input.addEventListener('input', handleInput); function handleFocus(event) { event.target.style.backgroundColor = 'lightblue'; } function handleBlur(event) { event.target.style.backgroundColor = 'white'; } function handleInput(event) { console.log('Input value:', event.target.value); }

8. Asynchronous JavaScript

Promises

// Creating a promise let myPromise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Operation successful!"); } else { reject("Operation failed!"); } }); // Using promises myPromise .then(result => { console.log(result); }) .catch(error => { console.error(error); });

Async/Await

// Async function async function fetchData() { try { let response = await fetch('https://api.example.com/data'); let data = await response.json(); return data; } catch (error) { console.error('Error fetching data:', error); } } // Using async function fetchData().then(data => { console.log(data); });

9. ES6+ Features

Destructuring

// Array destructuring let [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(rest); // [3, 4, 5] // Object destructuring let {name, age, city = "Unknown"} = {name: "John", age: 30}; console.log(name); // "John" console.log(city); // "Unknown"

Template Literals

let name = "Alice"; let age = 25; // Template literal let message = `Hello, my name is ${name} and I'm ${age} years old.`; // Multi-line strings let multiLine = ` This is a multi-line string `;

Modules

// Exporting (math.js) export function add(a, b) { return a + b; } export const PI = 3.14159; export default function multiply(a, b) { return a * b; } // Importing (main.js) import multiply, { add, PI } from './math.js'; import * as math from './math.js'; console.log(add(2, 3)); // 5 console.log(multiply(4, 5)); // 20 console.log(PI); // 3.14159

10. Practice Projects

Calculator Project

Interactive Calculator

🏋️ Final Projects:

Build these projects to practice your JavaScript skills:

  • To-Do List: Add, edit, delete, and mark tasks as complete
  • Weather App: Fetch weather data from an API
  • Quiz Game: Multiple choice questions with scoring
  • Memory Game: Card matching game
  • Shopping Cart: Add/remove items, calculate totals