Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
14 views50 pages

Output

Uploaded by

Saravanan K G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views50 pages

Output

Uploaded by

Saravanan K G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Complete JavaScript + Web

Development Mastery Course


From Zero to Beyond Mastery
Welcome to the most comprehensive JavaScript course ever created! This course will
take you from knowing absolutely nothing about computers to becoming a
JavaScript master who can build amazing websites and web applications.

Table of Contents
Phase 1: Foundation Knowledge (Chapters 1-3)

1. What is a Computer and the Internet?


2. Introduction to Web Pages (HTML & CSS Basics)
3. What is JavaScript and Why Do We Need It?

Phase 2: JavaScript Fundamentals (Chapters 4-12)

1. Setting Up Your Development Environment


2. Your First JavaScript Code
3. Variables and Data Storage
4. Data Types - Understanding Different Kinds of Information
5. Operators - Making JavaScript Do Math and Logic
6. Control Flow - Making Decisions in Code
7. Functions - Creating Reusable Code Blocks
8. Arrays - Storing Lists of Information
9. Objects - Organizing Related Information

Phase 3: Advanced JavaScript Concepts (Chapters 13-20)

1. Scope and Closures - Understanding Where Variables Live


2. Hoisting - How JavaScript Reads Your Code
3. The this Keyword - Understanding Context
4. Prototypes and Inheritance - How Objects Share Properties
5. ES6+ Modern JavaScript Features
6. Error Handling - Dealing with Problems
7. Asynchronous JavaScript - Handling Time and Waiting
8. Modules - Organizing Your Code
Phase 4: JavaScript in the Browser (Chapters 21-27)

1. The Document Object Model (DOM)


2. Selecting and Manipulating Elements
3. Events - Making Your Website Interactive
4. Forms - Getting User Input
5. Timing Functions and Animations
6. Browser Storage - Remembering User Data
7. Best Practices for Web Development

Phase 5: Master Level Projects and Assessment (Chapters 28-30)

1. Building Real Applications


2. Advanced Techniques and Performance
3. Final Assessment and Next Steps

Phase 1: Foundation Knowledge


Chapter 1: What is a Computer and the Internet?

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

What is the Internet?

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.

Chapter 2: Introduction to Web Pages (HTML & CSS Basics)

What Makes a Web Page?

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 - The Structure

HTML stands for "HyperText Markup Language." It's like the blueprint for a web
page. It tells the browser what parts go where.

Basic HTML Example:

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 - The Style

CSS stands for "Cascading Style Sheets." It makes web pages look pretty by
controlling colors, sizes, and positions.

Basic CSS Example:


css
h1 {
color: blue;
font-size: 24px;
}

p {
color: green;
}

button {
background-color: yellow;
padding: 10px;
}

How HTML and CSS Work Together

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!

Chapter 3: What is JavaScript and Why Do We Need It?

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.

Why Do We Need JavaScript?

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

• 1995: JavaScript was created by Brendan Eich in just 10 days


• 1997: JavaScript became an official standard
• 2000s: JavaScript became more popular with websites like Gmail
• 2010s: JavaScript started being used for mobile apps and even server programs
• Today: JavaScript is one of the most popular programming languages in the
world

JavaScript vs Other Programming Languages

• 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!

Phase 2: JavaScript Fundamentals


Chapter 4: Setting Up Your Development Environment

What is a Development Environment?

A development environment is like a workshop where you build things. For


JavaScript, you need: 1. A text editor to write code 2. A web browser to test your code
3. Developer tools to debug your code

Text Editors for Beginners

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

Setting up VS Code: 1. Download VS Code from code.visualstudio.com 2. Install


these helpful extensions: - Live Server - Prettier - ES7+ React/Redux/React-Native
snippets
Browser Developer Tools

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!

Your First JavaScript Setup

1. Create a new folder called "JavaScript-Learning"


2. Create a file called "index.html"
3. Create a file called "script.js"
4. Open VS Code and open your folder

Basic HTML Template:

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!

Chapter 5: Your First JavaScript Code

Writing Your First JavaScript

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

Understanding the Console

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
*/

Basic JavaScript Syntax Rules

1. Case Sensitive: console.log is different from Console.Log


2. Semicolons: End statements with semicolons (;)
3. Quotes: Use quotes around text (" or ')
4. Parentheses: Functions need parentheses ()
5. Brackets: Use {} to group code together

Different Ways to Run JavaScript

1. In the Console:
javascript
console.log("This runs in the console");

2. Alert Boxes:

javascript
alert("This shows a popup message");

3. Writing to the Web Page:

javascript
document.write("This writes directly to the page");

4. Changing HTML Content:

javascript
document.getElementById("demo").innerHTML = "This changes HTML content";

Practice Exercise 5.1: Hello Messages

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

Practice Exercise 5.2: Personal Introduction

Write a script that introduces you with your name, age, and favorite color using
console.log.

Practice Exercise 5.3: Comment Practice

Take your introduction script and add comments explaining what each line does.

Mini-Quiz 5.1

1. What does console.log() do?


2. What are the two types of comments in JavaScript?
3. True or False: console.log and Console.Log are the same thing.
4. What character do you use to end a statement in JavaScript?
Chapter 6: Variables and Data Storage

What are Variables?

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

Creating Variables in JavaScript

There are three ways to create variables:

1. var (the old way):

javascript
var myName = "Alex";
var myAge = 25;

2. let (the new way for changeable variables):

javascript
let myName = "Alex";
let myAge = 25;

3. const (for variables that never change):

javascript
const myBirthday = "January 1st";
const pi = 3.14159;

Variable Naming Rules

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)

Good variable names:

javascript
let firstName = "John";
let age = 25;
let isStudent = true;
let totalScore = 100;

Bad variable names:

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

Variable Naming Best Practices

Use camelCase: Start with lowercase, capitalize each new word

javascript
let myFavoriteColor = "blue";
let numberOfPets = 3;
let isLoggedIn = true;

Use descriptive names:

javascript
// Good
let userEmail = "[email protected]";
let shoppingCartTotal = 29.99;

// Bad
let x = "[email protected]";
let y = 29.99;

Changing Variable Values

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

let - Use for variables that can change:

javascript
let temperature = 72;
temperature = 75; // This is okay

const - Use for variables that never change:

javascript
const myName = "Alex";
myName = "Bob"; // This will cause an error!

var - The old way (avoid using):

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"

Practice Exercise 6.1: Variable Creation

Create variables for: 1. Your first name 2. Your age 3. Your favorite number 4.
Whether you like pizza (true or false)

Practice Exercise 6.2: Variable Changes

1. Create a variable called points and set it to 0


2. Add 10 points to it
3. Add 5 more points
4. Display the final value in the console
Practice Exercise 6.3: Personal Profile

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

1. What's the difference between let and const?


2. Can you change the value of a const variable?
3. What naming convention does JavaScript use for variables?
4. True or False: Variable names can start with a number.

Chapter 7: Data Types - Understanding Different Kinds of


Information

What are Data Types?

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 has several data types for different kinds of information.

Primitive Data Types

1. Numbers Numbers are used for counting, math, and measurements.

javascript
let age = 25;
let price = 19.99;
let temperature = -5;
let bigNumber = 1000000;

Special number values:

javascript
let infinity = Infinity;
let notANumber = NaN; // "Not a Number"

2. Strings Strings are text - letters, words, sentences, or any characters.


javascript
let name = "Alice";
let message = 'Hello, world!';
let empty = "";
let mixedText = "I am 25 years old";

String quotes: - Use double quotes: "Hello" - Use single quotes: 'Hello' - Use
template literals: `Hello`

3. Booleans Booleans are true or false values - like yes/no or on/off.

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

5. Null Null means "intentionally empty" or "no value."

javascript
let data = null; // Intentionally empty

Checking Data Types

Use typeof to see what type of data you have:

javascript
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"

Working with Numbers

JavaScript can do math with numbers:


javascript
let a = 10;
let 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)

Working with Strings

You can combine strings and do other operations:

javascript
let firstName = "John";
let lastName = "Doe";

// Combining strings (concatenation)


let fullName = firstName + " " + lastName;
console.log(fullName); // "John 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 (Modern String Method)

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.";

// New way (template literals)


let message2 = `Hi, I'm ${name} and I'm ${age} years old.`;

console.log(message2); // "Hi, I'm Sarah and I'm 16 years old."


Type Conversion

Sometimes you need to change data from one type to another:

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

Common Type Conversion Mistakes

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)

Practice Exercise 7.1: Data Type Explorer

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 simple calculator that: 1. Stores two numbers in variables 2. Performs


addition, subtraction, multiplication, and division 3. Displays the results

Practice Exercise 7.3: Mad Libs

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

Practice Exercise 7.4: Type Conversion Practice

1. Create a string that contains a number


2. Convert it to a real number
3. Do math with it
4. Convert the result back to a string

Mini-Quiz 7.1

1. What are the 5 primitive data types in JavaScript?


2. What's the difference between null and undefined?
3. What operator do you use to check a variable's type?
4. What happens when you add a string and a number?

Chapter 8: Operators - Making JavaScript Do Math and Logic

What are Operators?

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.

Types of operators: - Arithmetic (math) - Assignment (storing values) -


Comparison (comparing values) - Logical (true/false logic) - String operators

Arithmetic Operators

These operators do math:

javascript
let a = 10;
let 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 (remainder/modulo)
console.log(a ** b); // 1000 (exponentiation - a to the power of b)

The Modulo Operator (%)

The modulo operator gives you the remainder after division:

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)

// Useful for checking if a number is even or odd


let number = 7;
if (number % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}

Assignment Operators

These operators assign values to variables:

javascript
let x = 10; // Basic assignment

// Compound assignment operators


x += 5; // Same as: x = x + 5 (x becomes 15)
x -= 3; // Same as: x = x - 3 (x becomes 12)
x *= 2; // Same as: x = x * 2 (x becomes 24)
x /= 4; // Same as: x = x / 4 (x becomes 6)
x %= 3; // Same as: x = x % 3 (x becomes 0)

Increment and Decrement Operators

Special operators for adding or subtracting 1:


javascript
let count = 5;

count++; // Increment (add 1) - count becomes 6


count--; // Decrement (subtract 1) - count becomes 5

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

These operators compare values and return true or false:

javascript
let a = 10;
let b = 5;

console.log(a > b); // true (greater than)


console.log(a < b); // false (less than)
console.log(a >= b); // true (greater than or equal)
console.log(a <= b); // false (less than or equal)
console.log(a == b); // false (equal value)
console.log(a != b); // true (not equal value)
console.log(a === b); // false (strictly equal)
console.log(a !== b); // true (strictly not equal)

Equality: == vs ===

Double equals (==) - Loose equality:

javascript
console.log(5 == "5"); // true (converts string to number)
console.log(true == 1); // true (converts boolean to number)
console.log(null == undefined); // true

Triple equals (===) - Strict equality:


javascript
console.log(5 === "5"); // false (different types)
console.log(true === 1); // false (different types)
console.log(null === undefined); // false

Best Practice: Always use === and !== unless you specifically need type conversion.

Logical Operators

These operators work with true/false values:

javascript
let isRaining = true;
let hasUmbrella = false;

// AND operator (&&) - both conditions must be true


console.log(isRaining && hasUmbrella); // false

// OR operator (||) - at least one condition must be true


console.log(isRaining || hasUmbrella); // true

// NOT operator (!) - flips true/false


console.log(!isRaining); // false
console.log(!hasUmbrella); // true

Logical Operators with Non-Boolean Values

JavaScript treats some values as "truthy" and others as "falsy":

Falsy values: - false - 0 - "" (empty string) - null - undefined - NaN

Everything else is truthy:

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

The + operator can combine strings:

javascript
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // "John Doe"

// You can also use += with strings


let message = "Hello";
message += " World";
console.log(message); // "Hello World"

Operator Precedence

JavaScript follows rules about which operators to do first:

javascript
let result = 5 + 3 * 2; // Multiplication first: 5 + 6 = 11
console.log(result); // 11

// Use parentheses to change order


let result2 = (5 + 3) * 2; // Parentheses first: 8 * 2 = 16
console.log(result2); // 16

Common precedence order (highest to lowest): 1. Parentheses () 2.


Exponentiation ** 3. Multiplication *, Division /, Modulo % 4. Addition +, Subtraction
- 5. Comparison <, >, <=, >= 6. Equality ==, ===, !=, !== 7. Logical AND && 8. Logical OR
|| 9. Assignment =, +=, -=, etc.

Practice Exercise 8.1: Math Calculator

Create a calculator that: 1. Stores two numbers 2. Performs all arithmetic operations
3. Displays the results with descriptive messages

Practice Exercise 8.2: Comparison Practice

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

Practice Exercise 8.4: Even or Odd Checker

Create a program that checks if a number is even or odd using the modulo operator.

Practice Exercise 8.5: Grade Calculator

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

1. What does the modulo operator (%) do?


2. What's the difference between == and ===?
3. What are the three logical operators in JavaScript?
4. Which operation happens first: 5 + 3 * 2?
5. Name three falsy values in JavaScript.

Chapter 9: Control Flow - Making Decisions in Code

What is Control Flow?

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

The if statement lets your program make decisions:

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

The if-else Statement

Sometimes you want to do one thing if the condition is true, and something else if
it's false:

javascript
let age = 16;

if (age >= 18) {


console.log("You can vote!");
} else {
console.log("You're too young to vote yet.");
}

The else if Statement

For multiple conditions:

javascript
let grade = 85;

if (grade >= 90) {


console.log("A - Excellent!");
} else if (grade >= 80) {
console.log("B - Good job!");
} else if (grade >= 70) {
console.log("C - Passing");
} else if (grade >= 60) {
console.log("D - Below average");
} else {
console.log("F - Failing");
}

Nested if Statements

You can put if statements inside other if statements:


javascript
let weather = "sunny";
let temperature = 75;

if (weather === "sunny") {


if (temperature > 70) {
console.log("Perfect day for the beach!");
} else {
console.log("Sunny but too cold for the beach.");
}
} else {
console.log("Not a beach day.");
}

The switch Statement

When you have many possible values to check:

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)

A shortcut for simple if-else statements:

javascript
let age = 20;

// Long way
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}

// Short way (ternary operator)


let status = age >= 18 ? "adult" : "minor";

Syntax: condition ? valueIfTrue : valueIfFalse

Combining Conditions

You can combine multiple conditions using logical operators:

javascript
let age = 25;
let hasLicense = true;
let hasInsurance = true;

// Multiple conditions with AND


if (age >= 18 && hasLicense && hasInsurance) {
console.log("You can drive!");
} else {
console.log("You cannot drive yet.");
}

// Multiple conditions with OR


let isWeekend = true;
let isHoliday = false;

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.

The for Loop

Use when you know how many times to repeat:

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

The while Loop

Use when you don't know exactly how many times to repeat:

javascript
let count = 1;

while (count <= 5) {


console.log("Count: " + count);
count++; // Don't forget to increment!
}

Be careful! If you forget to increment, you'll create an infinite loop!

The do-while Loop

Runs at least once, then checks the condition:


javascript
let userInput;

do {
userInput = prompt("Enter 'quit' to exit:");
console.log("You entered: " + userInput);
} while (userInput !== "quit");

Breaking Out of Loops

Use break to exit a loop early:

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

Skipping Loop Iterations

Use continue to skip the rest of the current iteration:

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

Loops inside other loops:

javascript
for (let row = 1; row <= 3; row++) {
for (let col = 1; col <= 3; col++) {
console.log(`Row ${row}, Column ${col}`);
}
}

Common Loop Patterns

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
}

Practice Exercise 9.1: Grade Classifier

Create a program that: 1. Takes a numerical grade 2. Classifies it as A, B, C, D, or F 3.


Provides encouraging messages

Practice Exercise 9.2: Number Guessing Game

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

Practice Exercise 9.3: Multiplication Table

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

Practice Exercise 9.4: FizzBuzz

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

Practice Exercise 9.5: Password Validator

Create a password validator that checks if a password: 1. Is at least 8 characters long


2. Contains at least one uppercase letter 3. Contains at least one lowercase letter 4.
Contains at least one number

Mini-Quiz 9.1

1. What's the difference between if and switch statements?


2. What happens if you forget a break in a switch statement?
3. What's the difference between while and do-while loops?
4. What does the continue statement do in a loop?
5. How do you exit a loop early?

Chapter 10: Functions - Creating Reusable Code Blocks

What are Functions?

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

Creating Your First Function

Function Declaration:
javascript
function sayHello() {
console.log("Hello, World!");
}

// To use the function, you "call" it


sayHello(); // Output: Hello, World!

Functions with Parameters

Parameters are like ingredients you give to a recipe:

javascript
function greet(name) {
console.log("Hello, " + name + "!");
}

greet("Alice"); // Output: Hello, Alice!


greet("Bob"); // Output: Hello, Bob!

Multiple Parameters

Functions can take multiple inputs:

javascript
function introduce(name, age, city) {
console.log(`Hi, I'm ${name}. I'm ${age} years old and I live in ${city}.`);
}

introduce("Sarah", 16, "New York");


// Output: Hi, I'm Sarah. I'm 16 years old and I live in New York.

Return Values

Functions can give back results:

javascript
function add(a, b) {
return a + b;
}

let result = add(5, 3);


console.log(result); // 8
// You can use the return value directly
console.log(add(10, 20)); // 30

Function Expressions

Another way to create functions:

javascript
const multiply = function(a, b) {
return a * b;
};

console.log(multiply(4, 5)); // 20

Arrow Functions (ES6)

A shorter way to write functions:

javascript
// Traditional function
function square(x) {
return x * x;
}

// Arrow function
const square = (x) => {
return x * x;
};

// Even shorter arrow function (for single expressions)


const square = x => x * x;

console.log(square(4)); // 16

Default Parameters

You can give parameters default values:

javascript
function greet(name = "Friend") {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Hello, Alice!
greet(); // Hello, Friend!

Local vs Global Scope

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!");
}

But function expressions are NOT hoisted:

javascript
sayBye(); // This causes an error!

const sayBye = function() {


console.log("Goodbye!");
};

Functions Calling Other Functions

Functions can call other functions:


javascript
function formatName(firstName, lastName) {
return firstName + " " + lastName;
}

function createGreeting(firstName, lastName) {


let fullName = formatName(firstName, lastName);
return "Welcome, " + fullName + "!";
}

console.log(createGreeting("John", "Doe")); // Welcome, John Doe!

Recursive Functions

Functions that call themselves:

javascript
function countdown(n) {
if (n <= 0) {
console.log("Blast off!");
return;
}

console.log(n);
countdown(n - 1); // Function calls itself
}

countdown(5); // 5, 4, 3, 2, 1, Blast off!

Anonymous Functions

Functions without names, often used for short operations:

javascript
// Using an anonymous function with setTimeout
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);

// Arrow function version


setTimeout(() => {
console.log("This also runs after 2 seconds");
}, 2000);
Common Function Patterns

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";
}
}

console.log(calculate("add", 10, 5)); // 15

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();
}

function randomNumber(min, max) {


return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(capitalize("hello")); // Hello
console.log(randomNumber(1, 10)); // Random number between 1 and 10

Best Practices for Functions

1. Use descriptive names: calculateTax() not calc()


2. Keep functions small: One function should do one thing
3. Use parameters instead of global variables
4. Return values instead of printing inside functions
5. Add comments for complex functions

Practice Exercise 10.1: Basic Functions

Create functions for: 1. Converting Celsius to Fahrenheit 2. Calculating the area of a


rectangle 3. Checking if a number is even or odd 4. Finding the maximum of two
numbers

Practice Exercise 10.2: Personal Information

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

Practice Exercise 10.3: Math Library

Create a mini math library with functions for: 1. Addition, subtraction,


multiplication, division 2. Finding the square and square root 3. Calculating
percentage 4. Converting between different units

Practice Exercise 10.4: String Utilities

Create utility functions for: 1. Counting words in a sentence 2. Reversing a string 3.


Checking if a string is a palindrome 4. Removing spaces from a string

Practice Exercise 10.5: Game 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

1. What's the difference between parameters and arguments?


2. What does it mean for a function to "return" a value?
3. What's the difference between function declarations and function expressions?
4. What is function hoisting?
5. What's the scope of a variable declared inside a function?

Chapter 11: Arrays - Storing Lists of Information

What are Arrays?

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

Array Literal (most common way):

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

Accessing Array Elements

Arrays use index numbers starting from 0:

javascript
let fruits = ["apple", "banana", "orange"];

console.log(fruits[0]); // "apple" (first item)


console.log(fruits[1]); // "banana" (second item)
console.log(fruits[2]); // "orange" (third item)
console.log(fruits[3]); // undefined (doesn't exist)
Array Length

Find out how many items are in an array:

javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 3

Changing Array Elements

You can change items in an array:

javascript
let fruits = ["apple", "banana", "orange"];
fruits[1] = "grape";
console.log(fruits); // ["apple", "grape", "orange"]

Adding Elements to Arrays

Adding to the end:

javascript
let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]

// Add multiple items


fruits.push("grape", "kiwi");
console.log(fruits); // ["apple", "banana", "orange", "grape", "kiwi"]

Adding to the beginning:

javascript
let fruits = ["banana", "orange"];
fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "orange"]

Removing Elements from Arrays

Removing from the end:


javascript
let fruits = ["apple", "banana", "orange"];
let lastFruit = fruits.pop();
console.log(lastFruit); // "orange"
console.log(fruits); // ["apple", "banana"]

Removing from the beginning:

javascript
let fruits = ["apple", "banana", "orange"];
let firstFruit = fruits.shift();
console.log(firstFruit); // "apple"
console.log(fruits); // ["banana", "orange"]

Finding Elements in Arrays

Finding the index of an element:

javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.indexOf("banana")); // 1
console.log(fruits.indexOf("grape")); // -1 (not found)

Checking if an element exists:

javascript
let fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false

Looping Through Arrays

Using a for loop:

javascript
let fruits = ["apple", "banana", "orange"];

for (let i = 0; i < fruits.length; i++) {


console.log(fruits[i]);
}

Using a for...of loop:


javascript
let fruits = ["apple", "banana", "orange"];

for (let fruit of fruits) {


console.log(fruit);
}

Using forEach method:

javascript
let fruits = ["apple", "banana", "orange"];

fruits.forEach(function(fruit, index) {
console.log(index + ": " + fruit);
});

// Arrow function version


fruits.forEach((fruit, index) => {
console.log(index + ": " + fruit);
});

Array Methods

Joining array elements into a string:

javascript
let fruits = ["apple", "banana", "orange"];
let fruitString = fruits.join(", ");
console.log(fruitString); // "apple, banana, orange"

Splitting a string into an array:

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"]

// Sorting numbers (need a compare function)


let numbers = [10, 5, 20, 1];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 10, 20]

Slicing Arrays

Get a portion of an array without changing the original:

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

Remove/add elements at any position:

javascript
let fruits = ["apple", "banana", "orange"];

// Remove 1 element at index 1


let removed = fruits.splice(1, 1);
console.log(removed); // ["banana"]
console.log(fruits); // ["apple", "orange"]

// Add elements at index 1


fruits.splice(1, 0, "grape", "kiwi");
console.log(fruits); // ["apple", "grape", "kiwi", "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"]

Using spread operator:

javascript
let fruits = ["apple", "banana"];
let vegetables = ["carrot", "broccoli"];
let food = [...fruits, ...vegetables];
console.log(food); // ["apple", "banana", "carrot", "broccoli"]

Multi-dimensional Arrays

Arrays can contain other arrays:

javascript
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

console.log(matrix[0][1]); // 2 (first row, second column)


console.log(matrix[1][2]); // 6 (second row, third column)

Array Iteration Methods

map - Transform each element:

javascript
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

filter - Keep elements that meet a condition:

javascript
let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]

find - Find first element that meets a condition:


javascript
let numbers = [1, 2, 3, 4, 5];
let firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 2

reduce - Reduce array to a single value:

javascript
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15

Common Array Patterns

1. Finding the maximum/minimum:

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]

Practice Exercise 11.1: Shopping List

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)

Practice Exercise 11.3: To-Do List

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)

Practice Exercise 11.4: Number Analysis

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

Practice Exercise 11.5: Word Games

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

1. What index does the first element of an array have?


2. How do you add an element to the end of an array?
3. What's the difference between push() and unshift()?
4. How do you find the length of an array?
5. What does the indexOf() method return if the element is not found?

Chapter 12: Objects - Organizing Related Information

What are Objects?

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

Object Literal (most common way):

javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,
city: "New York"
};

Empty object:

javascript
let emptyObject = {};

Accessing Object Properties

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

// Useful when property name is in a variable


let property = "firstName";
console.log(person[property]); // "John"

Adding and Changing Properties

javascript
let person = {
firstName: "John",
lastName: "Doe"
};

// Add new property


person.age = 25;
person["city"] = "New York";

// Change existing property


person.age = 26;

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}

Objects with Methods

Objects can contain functions (called methods):

javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25,

// Method to get full name


getFullName: function() {
return this.firstName + " " + this.lastName;
},

// Method to introduce
introduce: function() {
return "Hi, I'm " + this.getFullName() + " and I'm " + this.age + " years old.";
}
};

console.log(person.getFullName()); // "John Doe"


console.log(person.introduce()); // "Hi, I'm John Doe and I'm 25 years old."

The this Keyword

Inside an object method, this refers to the object itself:

javascript
let car = {
brand: "Toyota",
model: "Camry",
year: 2020,

getInfo: function() {
return this.brand + " " + this.model + " (" + this.year + ")";
}
};

console.log(car.getInfo()); // "Toyota Camry (2020)"

Object Constructor Functions

Create multiple similar objects:

javascript
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;

this.getFullName = function() {
return this.firstName + " " + this.lastName;
};
}

let person1 = new Person("John", "Doe", 25);


let person2 = new Person("Jane", "Smith", 30);
console.log(person1.getFullName()); // "John Doe"
console.log(person2.getFullName()); // "Jane Smith"

Object.keys(), Object.values(), Object.entries()

Get information about object properties:

javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};

console.log(Object.keys(person)); // ["firstName", "lastName", "age"]


console.log(Object.values(person)); // ["John", "Doe", 25]
console.log(Object.entries(person)); // [["firstName", "John"], ["lastName", "Doe"], ["a

Looping Through Objects

Using for...in loop:

javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};

for (let key in person) {


console.log(key + ": " + person[key]);
}
// Output:
// 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

Objects can contain other objects:

javascript
let person = {
firstName: "John",
lastName: "Doe",
address: {
street: "123 Main St",
city: "New York",
zipCode: "10001"
},
hobbies: ["reading", "swimming", "coding"]
};

console.log(person.address.city); // "New York"


console.log(person.hobbies[0]); // "reading"

Arrays of Objects

Very common pattern in web development:

javascript
let students = [
{
name: "Alice",
grade: 85,
subject: "Math"
},
{
name: "Bob",
grade: 92,
subject: "Science"
},
{
name: "Charlie",
grade: 78,
subject: "English"
}
];

// Find student with highest grade


let topStudent = students.reduce((top, student) =>
student.grade > top.grade ? student : top
);

console.log(topStudent.name); // "Bob"

Object Methods and Properties

Checking if property exists:

javascript
let person = {
firstName: "John",
lastName: "Doe"
};

console.log("firstName" in person); // true


console.log("age" in person); // false
console.log(person.hasOwnProperty("firstName")); // true

Copying objects:

javascript
let person = {
firstName: "John",
lastName: "Doe"
};

// Shallow copy
let copy1 = Object.assign({}, person);
let copy2 = {...person}; // Spread operator

// Both copies are independent of the original


copy1.firstName = "Jane";
console.log(person.firstName); // Still "John"

JSON (JavaScript Object Notation)

Convert objects to strings and back:

javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 25
};

// Object to JSON string


let jsonString = JSON.stringify(person);
console.log(jsonString); // '{"firstName":"John","lastName":"Doe","age":25}'

// JSON string back to object


let parsedObject = JSON.parse(jsonString);
console.log(parsedObject.firstName); // "John"

Common Object Patterns

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);
}
};

3. API response objects:


javascript
let apiResponse = {
success: true,
data: {
users: [
{id: 1, name: "John"},
{id: 2, name: "Jane"}
]
},
message: "Users retrieved successfully"
};

Practice Exercise 12.1: Personal Profile

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

Practice Exercise 12.2: Library System

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

Practice Exercise 12.3: Shopping Cart

Create a shopping cart system: 1

You might also like