Complete Javascript + Web Development Mastery Course: From Zero To Beyond Mastery
Complete Javascript + Web Development Mastery Course: From Zero To Beyond Mastery
Table of Contents
Phase 1: Foundation Knowledge (Chapters 1-3)
What is a Computer?
A computer is like a very smart calculator that can follow instructions. Just like how
you might follow a recipe to bake cookies, a computer follows instructions called
"code" to do things.
Key Parts of a Computer: - Screen (Monitor): Where you see things - Keyboard:
Where you type - Mouse: How you point and click - Brain (CPU): The part that
thinks and follows instructions - Memory (RAM): Where the computer remembers
things temporarily - Storage (Hard Drive): Where the computer saves things
permanently
The Internet is like a giant library where computers can talk to each other and share
information. When you visit a website, your computer is asking another computer
(called a "server") to send you a web page.
Think of it like this: - You want to read a book (website) - You ask the librarian
(server) for the book - The librarian finds the book and gives it to you - You can now
read the book on your computer
What is a Web Browser?
A web browser is a special program that helps you look at websites. It's like a window
that shows you web pages. Common browsers include: - Chrome - Firefox - Safari -
Edge
Practice Exercise 1.1: Open your web browser and visit at least 3 different websites.
Notice how each one looks different but they all work in your browser.
Every web page is made of three main parts: 1. HTML - The structure (like the
skeleton of a house) 2. CSS - The style (like the paint and decorations) 3. JavaScript
- The behavior (like the lights and doors that work)
HTML stands for "HyperText Markup Language." It's like the blueprint for a web
page. It tells the browser what parts go where.
html
<!DOCTYPE html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>Welcome to My Website!</h1>
<p>This is my first paragraph.</p>
<button>Click Me!</button>
</body>
</html>
CSS stands for "Cascading Style Sheets." It makes web pages look pretty by
controlling colors, sizes, and positions.
p {
color: green;
}
button {
background-color: yellow;
padding: 10px;
}
HTML creates the parts, and CSS makes them look good. But neither one can make
the page interactive - that's where JavaScript comes in!
Practice Exercise 2.1: Create a simple HTML file with a heading, a paragraph, and a
button. Don't worry about making it work yet - we'll learn that with JavaScript!
What is JavaScript?
JavaScript is a programming language that makes web pages interactive. It's what
makes buttons work, forms submit, and websites respond to what you do.
JavaScript is NOT Java! They're completely different languages that just happen to
have similar names.
Without JavaScript, websites would be like books - you could read them, but you
couldn't interact with them. JavaScript lets you: - Click buttons and have things
happen - Fill out forms and submit them - Play games - Chat with friends - Watch
videos - And much more!
A Brief History of JavaScript
• Python: Great for beginners, often used for science and data
• Java: Used for big business applications
• C++: Used for video games and system programming
• JavaScript: The only language that runs in web browsers by default
Practice Exercise 3.1: Think of 5 websites you use regularly. For each one, write
down 3 things that happen when you click or interact with the page. All of those
interactions are powered by JavaScript!
Recommended editors: - Visual Studio Code (VS Code): Free, powerful, and
beginner-friendly - Sublime Text: Fast and simple - Atom: Easy to use with lots of
plugins
Every browser has built-in developer tools. To open them: - Chrome/Edge: Press
F12 or Ctrl+Shift+I - Firefox: Press F12 or Ctrl+Shift+I - Safari: Press Cmd+Option+I
The Console Tab: This is where you can type JavaScript code and see it run
immediately!
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning JavaScript</title>
</head>
<body>
<h1>My JavaScript Learning Journey</h1>
<script src="script.js"></script>
</body>
</html>
Practice Exercise 4.1: Set up your development environment and create your first
HTML file. Open it in your browser and make sure you can see the heading.
Practice Exercise 4.2: Open your browser's developer tools and find the Console
tab. Type 2 + 2 and press Enter. You just ran your first JavaScript code!
Let's start with the most traditional first program: "Hello, World!"
In your script.js file:
javascript
console.log("Hello, World!");
What does this do? - console.log() is a function that displays text in the browser's
console - The text inside the parentheses and quotes is what gets displayed
The console is like a communication channel between your code and you. It's where:
- Your program can show you messages - You can see error messages - You can test
small pieces of code
Comments in JavaScript
Comments are notes you write in your code that don't run. They help you remember
what your code does.
javascript
// This is a single-line comment
console.log("Hello, World!"); // This comment is at the end of a line
/*
This is a multi-line comment
You can write multiple lines here
Very useful for longer explanations
*/
1. In the Console:
javascript
console.log("This runs in the console");
2. Alert Boxes:
javascript
alert("This shows a popup message");
javascript
document.write("This writes directly to the page");
javascript
document.getElementById("demo").innerHTML = "This changes HTML content";
Create a script that displays three different messages: 1. One in the console 2. One
in an alert box 3. One written to the page
Write a script that introduces you with your name, age, and favorite color using
console.log.
Take your introduction script and add comments explaining what each line does.
Mini-Quiz 5.1
Variables are like boxes where you can store information. You can put things in the
box, look at what's in the box, and even change what's in the box.
Think of variables like: - A labeled box where you store toys - A parking space with
a number - A locker at school with your name on it
javascript
var myName = "Alex";
var myAge = 25;
javascript
let myName = "Alex";
let myAge = 25;
javascript
const myBirthday = "January 1st";
const pi = 3.14159;
Rules you MUST follow: - Must start with a letter, underscore (_), or dollar sign ($) -
Cannot start with a number - Cannot contain spaces - Cannot use reserved words
(like if, for, function)
javascript
let firstName = "John";
let age = 25;
let isStudent = true;
let totalScore = 100;
javascript
let 1name = "John"; // Can't start with number
let first name = "John"; // Can't have spaces
let if = "John"; // Can't use reserved words
javascript
let myFavoriteColor = "blue";
let numberOfPets = 3;
let isLoggedIn = true;
javascript
// Good
let userEmail = "[email protected]";
let shoppingCartTotal = 29.99;
// Bad
let x = "[email protected]";
let y = 29.99;
javascript
let score = 0;
console.log(score); // Shows: 0
score = 10;
console.log(score); // Shows: 10
score = score + 5;
console.log(score); // Shows: 15
The Difference Between let, var, and const
javascript
let temperature = 72;
temperature = 75; // This is okay
javascript
const myName = "Alex";
myName = "Bob"; // This will cause an error!
javascript
var oldVariable = "I'm old-fashioned";
Understanding Assignment
The = sign in programming doesn't mean "equals" like in math. It means "assign" or
"store."
javascript
let x = 5; // "Store the value 5 in variable x"
x = x + 1; // "Add 1 to x and store the result back in x"
Create variables for: 1. Your first name 2. Your age 3. Your favorite number 4.
Whether you like pizza (true or false)
Create a program that stores and displays: - Your name (use const because it won't
change) - Your age (use let because it changes every year) - Your grade in school
(use let) - Your favorite subject (use const)
Mini-Quiz 6.1
Data types are different categories of information, like how we have different types
of containers for different things: - A glass for water - A bowl for soup - A plate for
food
javascript
let age = 25;
let price = 19.99;
let temperature = -5;
let bigNumber = 1000000;
javascript
let infinity = Infinity;
let notANumber = NaN; // "Not a Number"
String quotes: - Use double quotes: "Hello" - Use single quotes: 'Hello' - Use
template literals: `Hello`
javascript
let isRaining = true;
let isSchoolDay = false;
let hasHomework = true;
4. Undefined Undefined means a variable has been created but no value has been
assigned.
javascript
let something;
console.log(something); // Shows: undefined
javascript
let data = null; // Intentionally empty
javascript
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
javascript
let firstName = "John";
let lastName = "Doe";
// String length
console.log(fullName.length); // 8
// Making uppercase/lowercase
console.log(fullName.toUpperCase()); // "JOHN DOE"
console.log(fullName.toLowerCase()); // "john doe"
Template literals use backticks (`) and allow you to insert variables easily:
javascript
let name = "Sarah";
let age = 16;
// Old way
let message1 = "Hi, I'm " + name + " and I'm " + age + " years old.";
Converting to Number:
javascript
let stringNumber = "25";
let realNumber = Number(stringNumber);
console.log(realNumber + 5); // 30
Converting to String:
javascript
let number = 42;
let text = String(number);
console.log(text + " is my favorite number"); // "42 is my favorite number"
Converting to Boolean:
javascript
let zero = 0;
let empty = "";
let something = "hello";
console.log(Boolean(zero)); // false
console.log(Boolean(empty)); // false
console.log(Boolean(something)); // true
javascript
// This might surprise you!
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (number subtraction)
console.log("5" * 3); // 15 (number multiplication)
Create variables of each data type and use typeof to check them: 1. A number 2. A
string 3. A boolean 4. An undefined variable 5. A null variable
Practice Exercise 7.2: Calculator
Create a Mad Libs game using template literals: 1. Create variables for a name,
adjective, noun, and verb 2. Use template literals to create a funny sentence 3.
Display the result
Mini-Quiz 7.1
Operators are symbols that tell JavaScript to perform specific operations. They're
like the buttons on a calculator or the action words in a sentence.
Arithmetic Operators
javascript
let a = 10;
let b = 3;
javascript
console.log(10 % 3); // 1 (10 ÷ 3 = 3 remainder 1)
console.log(15 % 4); // 3 (15 ÷ 4 = 3 remainder 3)
console.log(20 % 5); // 0 (20 ÷ 5 = 4 remainder 0)
Assignment Operators
javascript
let x = 10; // Basic assignment
// Pre-increment vs Post-increment
let a = 5;
let b = ++a; // Pre-increment: a becomes 6, then b gets 6
console.log(a, b); // 6, 6
let c = 5;
let d = c++; // Post-increment: d gets 5, then c becomes 6
console.log(c, d); // 6, 5
Comparison Operators
javascript
let a = 10;
let b = 5;
Equality: == vs ===
javascript
console.log(5 == "5"); // true (converts string to number)
console.log(true == 1); // true (converts boolean to number)
console.log(null == undefined); // true
Best Practice: Always use === and !== unless you specifically need type conversion.
Logical Operators
javascript
let isRaining = true;
let hasUmbrella = false;
javascript
console.log(Boolean("hello")); // true
console.log(Boolean(42)); // true
console.log(Boolean([])); // true
console.log(Boolean({})); // true
console.log(Boolean("")); // false
console.log(Boolean(0)); // false
String Operators
javascript
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // "John Doe"
Operator Precedence
javascript
let result = 5 + 3 * 2; // Multiplication first: 5 + 6 = 11
console.log(result); // 11
Create a calculator that: 1. Stores two numbers 2. Performs all arithmetic operations
3. Displays the results with descriptive messages
Create variables for your age and your friend's age, then compare them using all
comparison operators.
Practice Exercise 8.3: Logical Thinking
Create a program that checks if it's a good day to go to the beach: - It's sunny (true/
false) - Temperature is above 75°F - It's not raining - Use logical operators to
determine if it's a good beach day
Create a program that checks if a number is even or odd using the modulo operator.
Create a program that: 1. Stores test scores for 3 tests 2. Calculates the average 3.
Determines if the student passed (average >= 70)
Mini-Quiz 8.1
Control flow is how your program makes decisions and chooses what to do next. It's
like following a recipe that has different steps depending on what ingredients you
have.
Think of it like: - If it's raining, take an umbrella - If you're hungry, eat something - If
you finished your homework, you can play games
The if Statement
javascript
let temperature = 75;
if (temperature > 70) {
console.log("It's a nice day!");
}
How it works: 1. JavaScript checks if the condition is true 2. If true, it runs the code
inside the {} 3. If false, it skips that code
Sometimes you want to do one thing if the condition is true, and something else if
it's false:
javascript
let age = 16;
javascript
let grade = 85;
Nested if Statements
javascript
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week");
break;
case "Tuesday":
console.log("Tuesday blues");
break;
case "Wednesday":
console.log("Hump day!");
break;
case "Thursday":
console.log("Almost Friday");
break;
case "Friday":
console.log("TGIF!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Not a valid day");
}
Important: Don't forget the break statements! Without them, the code keeps
running through all the cases.
The Ternary Operator (Conditional Operator)
javascript
let age = 20;
// Long way
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}
Combining Conditions
javascript
let age = 25;
let hasLicense = true;
let hasInsurance = true;
if (isWeekend || isHoliday) {
console.log("No school today!");
} else {
console.log("Time for school.");
}
Loops - Repeating Actions
What are Loops? Loops let you repeat code multiple times without writing it over
and over. It's like telling someone "do this 10 times" instead of saying "do this" 10
separate times.
javascript
// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log("Count: " + i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5
How it works: 1. let i = 1 - Start with i = 1 2. i <= 5 - Keep going while i is 5 or less
3. i++ - Add 1 to i after each loop
Use when you don't know exactly how many times to repeat:
javascript
let count = 1;
do {
userInput = prompt("Enter 'quit' to exit:");
console.log("You entered: " + userInput);
} while (userInput !== "quit");
javascript
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // Exit the loop when i equals 5
}
console.log(i);
}
// Output: 1, 2, 3, 4
javascript
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip when i equals 3
}
console.log(i);
}
// Output: 1, 2, 4, 5
Nested Loops
javascript
for (let row = 1; row <= 3; row++) {
for (let col = 1; col <= 3; col++) {
console.log(`Row ${row}, Column ${col}`);
}
}
1. Counting up:
javascript
for (let i = 0; i < 10; i++) {
console.log(i);
}
2. Counting down:
javascript
for (let i = 10; i > 0; i--) {
console.log(i);
}
3. Counting by twos:
javascript
for (let i = 0; i <= 10; i += 2) {
console.log(i); // 0, 2, 4, 6, 8, 10
}
Create a simple number guessing game: 1. Pick a secret number between 1 and 10 2.
Ask the user to guess 3. Tell them if their guess is too high, too low, or correct 4. Use
a loop to let them keep guessing
Create a program that prints the multiplication table for a given number:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
... and so on
Create the classic FizzBuzz program: 1. Count from 1 to 100 2. If the number is
divisible by 3, print "Fizz" 3. If divisible by 5, print "Buzz" 4. If divisible by both 3 and
5, print "FizzBuzz" 5. Otherwise, print the number
Mini-Quiz 9.1
Functions are like recipes - they're a set of instructions that you can use over and
over again. Instead of writing the same code multiple times, you create a function
once and then "call" it whenever you need it.
Think of functions like: - A recipe you can follow to make cookies - A machine that
takes inputs and gives outputs - A magic spell that does something when you say its
name
Function Declaration:
javascript
function sayHello() {
console.log("Hello, World!");
}
javascript
function greet(name) {
console.log("Hello, " + name + "!");
}
Multiple Parameters
javascript
function introduce(name, age, city) {
console.log(`Hi, I'm ${name}. I'm ${age} years old and I live in ${city}.`);
}
Return Values
javascript
function add(a, b) {
return a + b;
}
Function Expressions
javascript
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // 20
javascript
// Traditional function
function square(x) {
return x * x;
}
// Arrow function
const square = (x) => {
return x * x;
};
console.log(square(4)); // 16
Default Parameters
javascript
function greet(name = "Friend") {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Hello, Alice!
greet(); // Hello, Friend!
Variables inside functions are "local" - they only exist inside the function:
javascript
let globalVar = "I'm global";
function myFunction() {
let localVar = "I'm local";
console.log(globalVar); // Can access global variables
console.log(localVar); // Can access local variables
}
myFunction();
console.log(globalVar); // Works fine
console.log(localVar); // Error! localVar doesn't exist here
Function Hoisting
Function declarations are "hoisted" - you can call them before they're defined:
javascript
sayHi(); // This works!
function sayHi() {
console.log("Hi there!");
}
javascript
sayBye(); // This causes an error!
Recursive Functions
javascript
function countdown(n) {
if (n <= 0) {
console.log("Blast off!");
return;
}
console.log(n);
countdown(n - 1); // Function calls itself
}
Anonymous Functions
javascript
// Using an anonymous function with setTimeout
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
1. Calculator Functions:
javascript
function calculate(operation, a, b) {
switch(operation) {
case "add":
return a + b;
case "subtract":
return a - b;
case "multiply":
return a * b;
case "divide":
return a / b;
default:
return "Invalid operation";
}
}
2. Validation Functions:
javascript
function isValidEmail(email) {
return email.includes("@") && email.includes(".");
}
function isValidAge(age) {
return age >= 0 && age <= 120;
}
console.log(isValidEmail("[email protected]")); // true
console.log(isValidAge(25)); // true
3. Utility Functions:
javascript
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
Create functions that: 1. Format a full name (first + last) 2. Calculate age from birth
year 3. Create a profile summary using the other functions
Create functions for a simple game: 1. Generate a random number 2. Check if a guess
is correct 3. Keep track of attempts 4. Display game status
Mini-Quiz 10.1
Arrays are like containers that can hold multiple pieces of information in order.
Think of them as: - A shopping list with multiple items - A playlist with multiple
songs - A box with multiple toys, each in a numbered slot
Creating Arrays
javascript
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = ["hello", 42, true, "world"];
let empty = [];
Array Constructor:
javascript
let colors = new Array("red", "green", "blue");
let scores = new Array(5); // Creates array with 5 empty slots
javascript
let fruits = ["apple", "banana", "orange"];
javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 3
javascript
let fruits = ["apple", "banana", "orange"];
fruits[1] = "grape";
console.log(fruits); // ["apple", "grape", "orange"]
javascript
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
javascript
let fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "orange"]
javascript
let fruits = ["apple", "banana", "orange"];
let firstFruit = fruits.shift();
console.log(firstFruit); // "apple"
console.log(fruits); // ["banana", "orange"]
javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.indexOf("banana")); // 1
console.log(fruits.indexOf("grape")); // -1 (not found)
javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false
javascript
let fruits = ["apple", "banana", "orange"];
javascript
let fruits = ["apple", "banana", "orange"];
fruits.forEach(function(fruit, index) {
console.log(index + ": " + fruit);
});
Array Methods
javascript
let fruits = ["apple", "banana", "orange"];
let fruitString = fruits.join(", ");
console.log(fruitString); // "apple, banana, orange"
javascript
let sentence = "Hello world from JavaScript";
let words = sentence.split(" ");
console.log(words); // ["Hello", "world", "from", "JavaScript"]
Reversing an array:
javascript
let numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1]
Sorting an array:
javascript
let fruits = ["banana", "apple", "orange"];
fruits.sort();
console.log(fruits); // ["apple", "banana", "orange"]
Slicing Arrays
javascript
let fruits = ["apple", "banana", "orange", "grape", "kiwi"];
let someFruits = fruits.slice(1, 3);
console.log(someFruits); // ["banana", "orange"]
console.log(fruits); // Original array unchanged
Splicing Arrays
javascript
let fruits = ["apple", "banana", "orange"];
Combining Arrays
Using concat:
javascript
let fruits = ["apple", "banana"];
let vegetables = ["carrot", "broccoli"];
let food = fruits.concat(vegetables);
console.log(food); // ["apple", "banana", "carrot", "broccoli"]
javascript
let fruits = ["apple", "banana"];
let vegetables = ["carrot", "broccoli"];
let food = [...fruits, ...vegetables];
console.log(food); // ["apple", "banana", "carrot", "broccoli"]
Multi-dimensional Arrays
javascript
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
javascript
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
javascript
let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]
javascript
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
javascript
let numbers = [5, 2, 8, 1, 9];
let max = Math.max(...numbers);
let min = Math.min(...numbers);
console.log(max); // 9
console.log(min); // 1
2. Removing duplicates:
javascript
let numbers = [1, 2, 2, 3, 3, 3, 4];
let unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4]
3. Flattening arrays:
javascript
let nested = [[1, 2], [3, 4], [5, 6]];
let flat = nested.flat();
console.log(flat); // [1, 2, 3, 4, 5, 6]
Create a shopping list application: 1. Create an array for your shopping list 2. Add
items to the list 3. Remove items when "bought" 4. Display the current list 5. Check if
a specific item is on the list
Practice Exercise 11.2: Grade Book
Create a grade book system: 1. Store student grades in an array 2. Calculate the
average grade 3. Find the highest and lowest grades 4. Count how many students
passed (grade >= 70)
Create a to-do list manager: 1. Add tasks to the list 2. Mark tasks as complete 3.
Remove completed tasks 4. Display remaining tasks 5. Show statistics (total tasks,
completed, remaining)
Create a program that analyzes an array of numbers: 1. Find even and odd numbers
2. Calculate sum and average 3. Find numbers greater than the average 4. Sort
numbers in ascending and descending order
Create word game functions: 1. Find the longest word in an array 2. Count words
that start with a specific letter 3. Create rhyming pairs 4. Sort words alphabetically
Mini-Quiz 11.1
Objects are like containers that hold related information together. Think of them as:
- A person's profile with name, age, and hobbies - A car with make, model, year, and
color - A book with title, author, pages, and genre
Unlike arrays that store items in order, objects store information in key-value pairs.
Creating Objects
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
city: "New York"
};
Empty object:
javascript
let emptyObject = {};
Dot notation:
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
console.log(person.firstName); // "John"
console.log(person.age); // 25
Bracket notation:
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
console.log(person["firstName"]); // "John"
console.log(person["age"]); // 25
javascript
let person = {
firstName: "John",
lastName: "Doe"
};
console.log(person); // {firstName: "John", lastName: "Doe", age: 26, city: "New York"}
Removing Properties
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
city: "New York"
};
delete person.city;
console.log(person); // {firstName: "John", lastName: "Doe", age: 25}
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
// Method to introduce
introduce: function() {
return "Hi, I'm " + this.getFullName() + " and I'm " + this.age + " years old.";
}
};
javascript
let car = {
brand: "Toyota",
model: "Camry",
year: 2020,
getInfo: function() {
return this.brand + " " + this.model + " (" + this.year + ")";
}
};
javascript
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.getFullName = function() {
return this.firstName + " " + this.lastName;
};
}
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
Using Object.keys():
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
Object.keys(person).forEach(key => {
console.log(key + ": " + person[key]);
});
Nested Objects
javascript
let person = {
firstName: "John",
lastName: "Doe",
address: {
street: "123 Main St",
city: "New York",
zipCode: "10001"
},
hobbies: ["reading", "swimming", "coding"]
};
Arrays of Objects
javascript
let students = [
{
name: "Alice",
grade: 85,
subject: "Math"
},
{
name: "Bob",
grade: 92,
subject: "Science"
},
{
name: "Charlie",
grade: 78,
subject: "English"
}
];
console.log(topStudent.name); // "Bob"
javascript
let person = {
firstName: "John",
lastName: "Doe"
};
Copying objects:
javascript
let person = {
firstName: "John",
lastName: "Doe"
};
// Shallow copy
let copy1 = Object.assign({}, person);
let copy2 = {...person}; // Spread operator
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};
1. Configuration objects:
javascript
let gameConfig = {
playerName: "Player1",
difficulty: "medium",
soundEnabled: true,
controls: {
up: "W",
down: "S",
left: "A",
right: "D"
}
};
2. Data models:
javascript
let product = {
id: 1,
name: "Laptop",
price: 999.99,
inStock: true,
category: "Electronics",
getDisplayPrice: function() {
return "$" + this.price.toFixed(2);
}
};
Create a personal profile object with: 1. Basic information (name, age, city) 2.
Hobbies array 3. Methods to introduce yourself 4. Method to add/remove hobbies
Create a library system with: 1. Book objects (title, author, pages, available) 2.
Methods to check out/return books 3. Search functionality 4. Display book
information
Create a shopping cart system: 1. Product objects with properties (name, price,
quantity) 2. Methods to add/remove products 3. Calculate total price 4. Apply
discounts 5. Display cart contents
Create a recipe book application: 1. Recipe objects with ingredients and instructions
2. Methods to scale recipes 3. Calculate cooking time 4. Search recipes by ingredient
5. Rate recipes
Mini-Quiz 12.1
What is Scope?
Scope determines where variables can be accessed in your code. Think of it like
rooms in a house: - Some things are in your bedroom (local scope) - Some things are
in the living room (function scope) - Some things are available throughout the house
(global scope)
Global Scope
function showMessage() {
console.log(globalMessage); // Can access global variable
}
Function Scope
Variables declared inside a function are only available inside that function:
javascript
function myFunction() {
let localMessage = "I'm only available inside this function";
console.log(localMessage); // This works
}
Block Scope
Variables declared with let and const inside blocks {} are block-scoped:
javascript
if (true) {
let blockVariable = "I'm in a block";
const anotherBlock = "Me too!";
var oldVariable = "I'm function-scoped";
}
Nested Scopes
javascript
let outerVariable = "I'm outer";
function outerFunction() {
let middleVariable = "I'm middle";
function innerFunction() {
let innerVariable = "I'm inner";
innerFunction();
}
outerFunction();
A closure is when an inner function has access to variables from its outer function,
even after the outer function has finished running.
javascript
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
1. Private Variables:
javascript
function createBankAccount(initialBalance) {
let balance = initialBalance;
return {
deposit: function(amount) {
balance += amount;
return balance;
},
withdraw: function(amount) {
if (amount <= balance) {
balance -= amount;
return balance;
} else {
return "Insufficient funds";
}
},
getBalance: function() {
return balance;
}
};
}
1. Function Factories:
javascript
function createMultiplier(multiplier) {
return function(number) {
return number * multiplier;
};
}
console.log(double(5)); // 10
console.log(triple(5)); // 15
javascript
// Problem: All functions log 3
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i); // Logs 3, 3, 3
}, 100);
}
What is Hoisting?
Function Hoisting
javascript
// This works because of hoisting
sayHello(); // "Hello!"
function sayHello() {
console.log("Hello!");
}
javascript
// This causes an error
sayGoodbye(); // TypeError: sayGoodbye is not a function
var sayGoodbye = function() {
console.log("Goodbye!");
};
javascript
console.log(myVar); // undefined (not an error)
var myVar = 5;
console.log(myVar); // 5
javascript
console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
let myLet = 5;
What is this?
The this keyword refers to the object that is currently executing the code. It's like a
pronoun that changes meaning depending on the context.
Global Context
javascript
console.log(this); // In browser: Window object
javascript
let person = {
name: "John",
greet: function() {
console.log("Hello, I'm " + this.name);
}
};
Function Context
javascript
function showThis() {
console.log(this);
}
let obj = {
method: showThis
};
obj.method(); // obj
Arrow functions don't have their own this - they inherit it from the enclosing scope:
javascript
let person = {
name: "John",
regularFunction: function() {
console.log("Regular:", this.name); // "John"
arrowFunction();
}
};
person.regularFunction();
Binding this
javascript
let person1 = { name: "John" };
let person2 = { name: "Jane" };
function greet() {
console.log("Hello, " + this.name);
}
Event Handlers:
javascript
let button = document.getElementById("myButton");
let obj = {
name: "MyObject",
handleClick: function() {
console.log(this.name); // undefined (this refers to button)
}
};
// Problem
button.addEventListener("click", obj.handleClick);
Every object in JavaScript has a prototype - another object that it inherits properties
and methods from. It's like a template or blueprint that objects can share.
When you try to access a property on an object, JavaScript looks: 1. On the object
itself 2. On the object's prototype 3. On the prototype's prototype 4. And so on, until
it finds the property or reaches the end
javascript
let animal = {
speak: function() {
console.log("Some generic animal sound");
}
};
javascript
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.getAge = function() {
return this.age;
};
javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return "Hello, I'm " + this.name;
}
getAge() {
return this.age;
}
}
javascript
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return this.name + " makes a sound";
}
}
speak() {
return this.name + " barks";
}
getBreed() {
return this.breed;
}
}
Prototype Methods
javascript
let person = {
name: "John",
age: 30
};
// Set prototype
let worker = Object.create(person);
worker.job = "Developer";
javascript
// Block scoped, can be reassigned
let name = "John";
name = "Jane"; // OK
Arrow Functions
javascript
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// Multiple lines
const greet = (name) => {
const message = "Hello, " + name;
return message;
};
// No parameters
const sayHello = () => "Hello!";
Template Literals
javascript
let name = "John";
let age = 30;
// Old way
let message = "Hello, my name is " + name + " and I'm " + age + " years old.";
// New way
let message = `Hello, my name is ${name} and I'm ${age} years old.`;
// Multi-line strings
let multiline = `
This is a
multi-line
string
`;
Destructuring Assignment
javascript
// Array destructuring
let colors = ["red", "green", "blue"];
let [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
// Object destructuring
let person = { name: "John", age: 30, city: "New York" };
let { name, age, city } = person;
console.log(name); // "John"
console.log(age); // 30
// Default values
let { name, age, country = "USA" } = person;
console.log(country); // "USA"
Spread Operator
javascript
// Array spread
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Object spread
let person = { name: "John", age: 30 };
let employee = { ...person, job: "Developer" };
console.log(employee); // { name: "John", age: 30, job: "Developer" }
// Function arguments
function sum(a, b, c) {
return a + b + c;
}
Rest Parameters
javascript
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
// Rest with other parameters
function greet(greeting, ...names) {
return greeting + " " + names.join(" and ");
}
console.log(greet("Hello", "John", "Jane", "Bob")); // "Hello John and Jane and Bob"
Default Parameters
javascript
function greet(name = "World", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
javascript
let name = "John";
let age = 30;
// Old way
let person = {
name: name,
age: age,
greet: function() {
return "Hello, I'm " + this.name;
}
};
// New way
let person = {
name, // Shorthand property
age,
greet() { // Shorthand method
return `Hello, I'm ${this.name}`;
}
};
Chapter 18: Error Handling - Dealing with Problems
Errors are problems that occur when your code runs. They're like roadblocks that
stop your program from working properly.
Types of Errors
Try-Catch-Finally
javascript
try {
// Code that might cause an error
let result = 10 / 0;
console.log(result);
} catch (error) {
// Handle the error
console.log("An error occurred:", error.message);
} finally {
// This always runs
console.log("Cleanup code here");
}
javascript
// ReferenceError - using undefined variable
try {
console.log(undefinedVariable);
} catch (error) {
console.log("ReferenceError:", error.message);
}
// TypeError - wrong type operation
try {
let number = 5;
number.toUpperCase(); // Numbers don't have toUpperCase
} catch (error) {
console.log("TypeError:", error.message);
}
javascript
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}
try {
let result = divide(10, 0);
console.log(result);
} catch (error) {
console.log("Error:", error.message);
}
javascript
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age) {
if (age < 0) {
throw new ValidationError("Age cannot be negative");
}
if (age > 150) {
throw new ValidationError("Age seems unrealistic");
}
return true;
}
try {
validateAge(-5);
} catch (error) {
if (error instanceof ValidationError) {
console.log("Validation failed:", error.message);
} else {
console.log("Unexpected error:", error.message);
}
}
javascript
// 1. Handle specific errors differently
function processUserData(userData) {
try {
// Validate data
if (!userData.email) {
throw new ValidationError("Email is required");
}
// Process data
let processed = JSON.parse(userData.preferences);
return processed;
} catch (error) {
if (error instanceof ValidationError) {
// Handle validation errors
console.log("Validation Error:", error.message);
return null;
} else if (error instanceof SyntaxError) {
// Handle JSON parsing errors
console.log("Invalid JSON format");
return {};
} else {
// Handle unexpected errors
console.log("Unexpected error:", error.message);
throw error; // Re-throw if we can't handle it
}
}
}
// 2. Graceful degradation
function getDataFromAPI() {
try {
// Simulate API call
throw new Error("Network error");
} catch (error) {
console.log("API failed, using cached data");
return { cached: true, data: [] };
}
}
Asynchronous programming allows your code to do other things while waiting for
slow operations (like loading data from the internet) to complete.
Think of it like: - Ordering food at a restaurant (you don't wait in the kitchen) -
Washing clothes (you don't stand and watch the machine) - Downloading files (you
can use your computer while it downloads)
javascript
// setTimeout - run code after a delay
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
if (counter >= 5) {
clearInterval(interval); // Stop the interval
}
}, 1000);
Callbacks
javascript
function fetchData(callback) {
setTimeout(() => {
let data = { id: 1, name: "John" };
callback(data);
}, 1000);
}
fetchData((data) => {
console.log("Received data:", data);
});
Callback Hell
javascript
// This gets messy quickly (callback hell)
getData((data) => {
processData(data, (processedData) => {
saveData(processedData, (result) => {
sendNotification(result, (notification) => {
console.log("All done!");
});
});
});
});
Promises
javascript
// Creating a promise
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let success = Math.random() > 0.5;
if (success) {
resolve({ id: 1, name: "John" });
} else {
reject(new Error("Failed to fetch data"));
}
}, 1000);
});
}
// Using a promise
fetchData()
.then((data) => {
console.log("Success:", data);
})
.catch((error) => {
console.log("Error:", error.message);
});
Chaining Promises
javascript
function fetchUser(id) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: id, name: "John" });
}, 1000);
});
}
function fetchUserPosts(userId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ id: 1, title: "Post 1", userId: userId },
{ id: 2, title: "Post 2", userId: userId }
]);
}, 1000);
});
}
// Promise chain
fetchUser(1)
.then((user) => {
console.log("User:", user);
return fetchUserPosts(user.id);
})
.then((posts) => {
console.log("Posts:", posts);
})
.catch((error) => {
console.log("Error:", error.message);
});
Async/Await
javascript
async function getUserData() {
try {
let user = await fetchUser(1);
console.log("User:", user);
} catch (error) {
console.log("Error:", error.message);
}
}
getUserData();
javascript
// Promise.all - wait for all promises to complete
async function loadAllData() {
try {
let [user, posts, comments] = await Promise.all([
fetchUser(1),
fetchUserPosts(1),
fetchComments(1)
]);
} catch (error) {
console.log("One of the requests failed:", error.message);
}
}
} catch (error) {
console.log("All servers failed:", error.message);
}
}
javascript
// Simulating API calls
function simulateAPICall(url, delay = 1000) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.1) { // 90% success rate
resolve({ url, data: `Data from ${url}` });
} else {
reject(new Error(`Failed to fetch ${url}`));
}
}, delay);
});
}
} catch (error) {
console.log("Failed to load page:", error.message);
}
}
loadPageData();
Modules are separate files that contain related code. They help you organize your
code into smaller, manageable pieces.
javascript
// Named exports
export function add(a, b) {
return a + b;
}
// Default export
export default function multiply(a, b) {
return a * b;
}
javascript
// Import specific functions
import { add, subtract, PI } from './math.js';
// Import everything
import * as math from './math.js';
console.log(add(5, 3)); // 8
console.log(subtract(10, 4)); // 6
console.log(PI); // 3.14159
console.log(multiply(2, 4)); // 8
javascript
// Pattern 1: Export as you declare
export function greet(name) {
return `Hello, ${name}!`;
}
function formatCurrency(amount) {
return `$${amount.toFixed(2)}`;
}
Module Patterns
javascript
export function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
config.js - Configuration:
javascript
export const API_URL = 'https://api.example.com';
export const MAX_RETRIES = 3;
export const TIMEOUT = 5000;
javascript
import { API_URL } from './config.js';
async save() {
// Save user to API
let response = await fetch(`${API_URL}/users`, {
method: 'POST',
body: JSON.stringify(this)
});
return response.json();
}
}
The DOM (Document Object Model) is how JavaScript sees and interacts with web
pages. It's like a family tree of all the HTML elements on a page.
Think of the DOM as: - A map of your house showing all the rooms - An organization
chart showing all employees - A family tree showing all relatives
```html
Welcome
This is a paragraph
Another paragraph