# Beginner-Friendly JavaScript Tutorial
This tutorial is designed for beginners learning JavaScript, a programming
language that makes websites interactive. Each topic and subtopic includes
simple explanations, examples, hints, additional notes, exercises, and
solutions to help you learn by doing. Let’s dive in!
---
## 1. Introduction to JavaScript
### What is JavaScript?
**Explanation**: JavaScript is a programming language that adds
interactivity to websites, like making buttons respond to clicks or updating
content without refreshing the page. It’s like the brain of a webpage,
controlling how it behaves. JavaScript is used in browsers (e.g., Chrome) and
can also run on servers with [Link].
**Example**:
```javascript
// Print a message to the browser's console
[Link]("Welcome to JavaScript!");
```
**Hints**:
- Open your browser’s developer tools (press F12, go to the Console tab) to
see `[Link]` output.
- JavaScript is case-sensitive, so `[Link]` won’t work—use
`[Link]`.
**Additional Notes**:
- JavaScript works with HTML (structure) and CSS (style) to create complete
websites.
- It’s beginner-friendly but powerful enough for complex apps like games or
chat systems.
**Exercise 1**: Write a script that logs “I’m learning JavaScript!” to the
console.
**Exercise 2**: Modify the script to log your name instead.
**Solutions**:
1. ```javascript
[Link]("I’m learning JavaScript!");
```
2. ```javascript
[Link]("YourName"); // Replace YourName with your actual name
```
---
### Why We Use JavaScript
**Explanation**: JavaScript makes websites dynamic by adding interactivity
(e.g., clicking a button to show a message), logic (e.g., checking if a form is
filled correctly), and behavior (e.g., animating images). It’s essential for
modern web apps like online stores or social media.
**Example**:
```javascript
// Alert the user when a button is clicked (we’ll learn events later)
alert("You clicked me!");
```
**Hints**:
- Think of JavaScript as what makes a website “respond” to you.
- Test small scripts in the browser console to see instant results.
**Additional Notes**:
- Common uses include form validation, real-time updates (e.g., live chat),
and animations.
- JavaScript is versatile, used in games, mobile apps, and even server-side
programming.
**Exercise 1**: Write a script that uses `alert` to display “Welcome to my
website!”.
**Exercise 2**: Use `[Link]` to print a reason why you want to learn
JavaScript.
**Solutions**:
1. ```javascript
alert("Welcome to my website!");
```
2. ```javascript
[Link]("I want to learn JavaScript to build interactive websites!");
```
---
### Where JavaScript Runs
**Explanation**: JavaScript runs in:
- **Browsers**: Inside Chrome, Firefox, etc., to control webpages.
- **[Link]**: On servers for backend tasks like handling databases.
**Example**:
```javascript
// This runs in a browser console
[Link]("JavaScript is running in the browser!");
```
**Hints**:
- Use your browser’s developer tools (F12) to experiment with JavaScript.
- [Link] requires installation, but browser JavaScript works immediately.
**Additional Notes**:
- Browsers have JavaScript engines (e.g., V8 in Chrome) to run code.
- [Link] lets JavaScript handle files or servers, but we’ll focus on browsers
for now.
**Exercise 1**: Open your browser console and run `[Link]("Hello from
the browser!");`.
**Exercise 2**: Write a script that logs “I’ll learn [Link] later!”.
**Solutions**:
1. Open F12, go to Console, type: ```javascript
[Link]("Hello from the browser!");
```
2. ```javascript
[Link]("I’ll learn [Link] later!");
```
---
### Embedding JavaScript in HTML
**Explanation**: You can add JavaScript to HTML in three ways:
- **Inline**: Code in HTML tags, e.g., `<button onclick="alert('Hi!')">`.
- **Internal**: Inside `<script>` tags in the HTML file.
- **External**: In a separate `.js` file linked with `<script src="[Link]">`.
**Example** (Internal):
```html
<!DOCTYPE html>
<html>
<body>
<script>
[Link]("Hello, JavaScript!");
</script>
</body>
</html>
```
**Example** (External):
```html
<!DOCTYPE html>
<html>
<body>
<script src="[Link]"></script>
</body>
</html>
// [Link]
[Link]("Hello from an external file!");
```
**Hints**:
- Place `<script>` at the end of `<body>` so HTML loads first.
- External files are best for keeping code organized.
**Additional Notes**:
- Inline is quick for testing but messy for big projects.
- External files can be reused across multiple HTML pages.
**Exercise 1**: Create an HTML file with an internal script that logs “Internal
script works!”.
**Exercise 2**: Create an external `.js` file that logs “External script works!”
and link it to an HTML file.
**Solutions**:
1. ```html
<!DOCTYPE html>
<html>
<body>
<script>
[Link]("Internal script works!");
</script>
</body>
</html>
```
2. ```html
<!DOCTYPE html>
<html>
<body>
<script src="[Link]"></script>
</body>
</html>
// [Link]
[Link]("External script works!");
```
---
## 2. Variables and Data Types
### `let`, `const`, `var`
**Explanation**: Variables store data like numbers or text. JavaScript has:
- `let`: Reassignable, limited to its block (e.g., inside `{}`).
- `const`: Cannot be reassigned, but its contents (e.g., arrays) can change.
- `var`: Older, less predictable, avoid it.
**Example**:
```javascript
let age = 25; // Can change
age = 26; // OK
const name = "Alice"; // Can’t change
// name = "Bob"; // Error!
var oldWay = 10; // Works but avoid
[Link](age, name, oldWay);
```
**Hints**:
- Use `const` for values that won’t change, `let` for those that will.
- Variable names should describe the data, e.g., `userAge` not `x`.
**Additional Notes**:
- `var` can cause bugs due to “hoisting” (code behaving unexpectedly).
- `const` arrays or objects can have their contents modified, e.g., adding to
an array.
**Exercise 1**: Declare a `let` variable for your age and change it by adding
1.
**Exercise 2**: Declare a `const` variable for your favorite color and try
(unsuccessfully) to reassign it.
**Solutions**:
1. ```javascript
let age = 20;
age = age + 1;
[Link](age); // 21
```
2. ```javascript
const color = "Blue";
// color = "Red"; // Error: Assignment to constant variable
[Link](color); // Blue
```
---
### Data Types
**Explanation**: JavaScript has several data types:
- **String**: Text, e.g., `"Hello"` or `'World'`.
- **Number**: Numbers, e.g., `42`, `3.14`.
- **Boolean**: `true` or `false`.
- **Null**: Empty value (set intentionally).
- **Undefined**: Variable with no value.
- **Object**: Key-value pairs, e.g., `{ name: "Alice" }`.
- **Array**: List, e.g., `["apple", "banana"]`.
**Example**:
```javascript
let str = "Hello"; // String
let num = 42; // Number
let isFun = true; // Boolean
let empty = null; // Null
let notSet; // Undefined
let person = { name: "Alice", age: 25 }; // Object
let fruits = ["apple", "banana"]; // Array
[Link](str, num, isFun, empty, notSet, person, fruits);
```
**Hints**:
- Use `typeof variable` to check a variable’s type.
- Strings need quotes; numbers don’t.
**Additional Notes**:
- JavaScript automatically determines types (dynamic typing).
- Arrays are a type of object but used for lists.
**Exercise 1**: Declare a variable for each data type and log them.
**Exercise 2**: Use `typeof` to check the type of a string and a number.
**Solutions**:
1. ```javascript
let text = "JavaScript";
let number = 100;
let isLearning = true;
let nothing = null;
let unknown;
let obj = { course: "JS" };
let arr = [1, 2, 3];
[Link](text, number, isLearning, nothing, unknown, obj, arr);
```
2. ```javascript
let text = "Hello";
let num = 10;
[Link](typeof text); // string
[Link](typeof num); // number
```
---
## 3. Operators
### Arithmetic Operators
**Explanation**: Perform math: `+` (add), `-` (subtract), `*` (multiply), `/`
(divide), `%` (modulus, gives remainder).
**Example**:
```javascript
let a = 10, b = 3;
[Link](a + b); // 13
[Link](a - b); // 7
[Link](a * b); // 30
[Link](a / b); // 3.333...
[Link](a % b); // 1 (remainder)
```
**Hints**:
- Use `()` to control operation order, e.g., `(2 + 3) * 4`.
- Modulus is great for checking even numbers (`num % 2 === 0`).
**Additional Notes**:
- Watch for division by zero (returns `Infinity`).
- Decimals can have small precision errors, e.g., `0.1 + 0.2` isn’t exactly
`0.3`.
**Exercise 1**: Calculate the area of a rectangle (length * width) and log it.
**Exercise 2**: Find the remainder of 15 divided by 4.
**Solutions**:
1. ```javascript
let length = 5, width = 3;
let area = length * width;
[Link](area); // 15
```
2. ```javascript
let num = 15;
[Link](num % 4); // 3
```
---
### Assignment Operators
**Explanation**: Assign or update values: `=` (assign), `+=` (add and
assign), `-=` (subtract and assign).
**Example**:
```javascript
let x = 10; // Assign
x += 5; // Same as x = x + 5
[Link](x); // 15
x -= 3; // Same as x = x - 3
[Link](x); // 12
```
**Hints**:
- Use `+=` for quick updates, like counting.
- Ensure the variable exists before using `+=` or `-=`.
**Additional Notes**:
- Other operators include `*=`, `/=`, `%=`.
- Saves typing and makes code cleaner.
**Exercise 1**: Use `+=` to add 10 to a variable starting at 20.
**Exercise 2**: Use `-=` to subtract 7 from a variable starting at 15.
**Solutions**:
1. ```javascript
let num = 20;
num += 10;
[Link](num); // 30
```
2. ```javascript
let num = 15;
num -= 7;
[Link](num); // 8
```
---
### Comparison Operators
**Explanation**: Compare values: `==` (loose equality), `===` (strict
equality), `!=` (not equal), `!==` (strict not equal), `>`, `<`, `>=`, `<=`.
**Example**:
```javascript
let a = 5, b = "5";
[Link](a == b); // true (loose, converts types)
[Link](a === b); // false (strict, checks type)
[Link](a != b); // false
[Link](a !== b); // true
[Link](a > 3); // true
```
**Hints**:
- Always use `===` to avoid type conversion surprises.
- Test with different types, e.g., `null == undefined` is `true`.
**Additional Notes**:
- `==` can lead to bugs, e.g., `"0" == false` is `true`.
- Use `<` and `>` for numbers, not strings (unless comparing
alphabetically).
**Exercise 1**: Check if 10 is strictly equal to “10” and log the result.
**Exercise 2**: Compare if 15 is greater than or equal to 10.
**Solutions**:
1. ```javascript
[Link](10 === "10"); // false
```
2. ```javascript
[Link](15 >= 10); // true
```
---
### Logical Operators
**Explanation**: Combine conditions: `&&` (AND, both true), `||` (OR, at
least one true), `!` (NOT, flips boolean).
**Example**:
```javascript
let age = 20, isStudent = true;
[Link](age > 18 && isStudent); // true (both true)
[Link](age > 25 || isStudent); // true (one true)
[Link](!isStudent); // false (flips true)
```
**Hints**:
- Use `&&` for multiple requirements, e.g., `age > 18 && hasTicket`.
- `||` is useful for defaults, e.g., `userInput || "Guest"`.
**Additional Notes**:
- Short-circuiting: `&&` stops if the first condition is false; `||` stops if the first
is true.
- `!` is useful for toggling booleans.
**Exercise 1**: Check if a number is between 10 and 20 (inclusive) using
`&&`.
**Exercise 2**: Use `||` to log “Adult” if age is 18 or older, else “Minor”.
**Solutions**:
1. ```javascript
let num = 15;
[Link](num >= 10 && num <= 20); // true
```
2. ```javascript
let age = 16;
[Link](age >= 18 || "Minor"); // Minor
```
---
## 4. Control Flow
### If, Else If, Else
**Explanation**: Run code based on conditions: `if (condition) { code } else
if (condition2) { code } else { code }`.
**Example**:
```javascript
let score = 85;
if (score >= 90) {
[Link]("A");
} else if (score >= 80) {
[Link]("B");
} else {
[Link]("C or below");
} // Logs: B
```
**Hints**:
- Conditions must evaluate to `true` or `false`.
- Use `{}` for clarity, even for one line.
**Additional Notes**:
- Nest `if` statements for complex logic, but keep it simple to avoid
confusion.
- Test all possible cases to ensure coverage.
**Exercise 1**: Write an `if` statement to check if a number is positive,
negative, or zero.
**Exercise 2**: Check if a person’s age is eligible to vote (18 or older).
**Solutions**:
1. ```javascript
let num = 0;
if (num > 0) {
[Link]("Positive");
} else if (num < 0) {
[Link]("Negative");
} else {
[Link]("Zero");
```
2. ```javascript
let age = 20;
if (age >= 18) {
[Link]("Eligible to vote");
} else {
[Link]("Not eligible");
```
---
### Switch
**Explanation**: Alternative to multiple `if` statements, checks a value
against cases: `switch (value) { case x: code; break; }`.
**Example**:
```javascript
let day = 2;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Other day");
} // Logs: Tuesday
```
**Hints**:
- Always include `break` to avoid running multiple cases.
- Use `default` for unexpected values.
**Additional Notes**:
- `switch` is cleaner for fixed values, like menu options.
- Use `if` for ranges or complex conditions.
**Exercise 1**: Write a `switch` statement for grades (A for 90+, B for 80+,
etc.).
**Exercise 2**: Use `switch` to log the name of a month based on its number
(1–12).
**Solutions**:
1. ```javascript
let score = 85;
switch (true) {
case score >= 90:
[Link]("A");
break;
case score >= 80:
[Link]("B");
break;
default:
[Link]("C or below");
```
2. ```javascript
let month = 3;
switch (month) {
case 1:
[Link]("January");
break;
case 3:
[Link]("March");
break;
default:
[Link]("Other month");
```
---
## 5. Loops
### For Loop
**Explanation**: Repeats code a set number of times: `for (init; condition;
update) { code }`.
**Example**:
```javascript
for (let i = 1; i <= 5; i++) {
[Link](i); // Logs: 1, 2, 3, 4, 5
```
**Hints**:
- Initialize with `let` to keep `i` local.
- Ensure the condition will eventually be false to avoid infinite loops.
**Additional Notes**:
- Useful for arrays or known iteration counts.
- `i++` means “add 1 to i”.
**Exercise 1**: Log numbers 1 to 10.
**Exercise 2**: Log “Hello” 3 times.
**Solutions**:
1. ```javascript
for (let i = 1; i <= 10; i++) {
[Link](i);
```
2. ```javascript
for (let i = 0; i < 3; i++) {
[Link]("Hello");
}
```
---
### While Loop
**Explanation**: Repeats while a condition is true: `while (condition)
{ code }`.
**Example**:
```javascript
let i = 1;
while (i <= 5) {
[Link](i); // Logs: 1, 2, 3, 4, 5
i++;
```
**Hints**:
- Update the condition variable (e.g., `i++`) to avoid infinite loops.
- Check the condition before starting.
**Additional Notes**:
- Use when the number of iterations is unknown.
- Similar to `for` but more flexible.
**Exercise 1**: Log numbers 5 to 1 (descending).
**Exercise 2**: Keep logging “Looping” until a counter reaches 4.
**Solutions**:
1. ```javascript
let i = 5;
while (i >= 1) {
[Link](i);
i--;
```
2. ```javascript
let count = 1;
while (count <= 4) {
[Link]("Looping");
count++;
```
---
### Do...While Loop
**Explanation**: Runs at least once, then repeats while the condition is true:
`do { code } while (condition)`.
**Example**:
```javascript
let i = 1;
do {
[Link](i); // Logs: 1, 2, 3
i++;
} while (i <= 3);
```
**Hints**:
- The code runs before checking the condition.
- Useful for menus or retry prompts.
**Additional Notes**:
- Less common but ensures at least one execution.
- Same infinite loop risk as `while`.
**Exercise 1**: Log “Try again” at least once, up to 3 times.
**Exercise 2**: Log numbers 1 to 4 using `do...while`.
**Solutions**:
1. ```javascript
let tries = 1;
do {
[Link]("Try again");
tries++;
} while (tries <= 3);
```
2. ```javascript
let i = 1;
do {
[Link](i);
i++;
} while (i <= 4);
```
---
### Break and Continue
**Explanation**:
- `break`: Stops the loop entirely.
- `continue`: Skips the current iteration.
**Example**:
```javascript
for (let i = 1; i <= 5; i++) {
if (i === 3) continue; // Skip 3
if (i === 5) break; // Stop at 5
[Link](i); // Logs: 1, 2, 4
```
**Hints**:
- Use `break` to exit early, e.g., when a condition is met.
- Use `continue` to skip unwanted values.
**Additional Notes**:
- Overusing `break` or `continue` can make code hard to read.
- Test to ensure the loop behaves as expected.
**Exercise 1**: Log numbers 1 to 10, skipping 7.
**Exercise 2**: Stop a loop at 5 when logging 1 to 10.
**Solutions**:
1. ```javascript
for (let i = 1; i <= 10; i++) {
if (i === 7) continue;
[Link](i);
```
2. ```javascript
for (let i = 1; i <= 10; i++) {
if (i === 5) break;
[Link](i);
```
---
## 6. Functions
### Function Declaration and Invocation
**Explanation**: Functions are reusable code blocks: `function name() { code
}`. Call them with `name()`.
**Example**:
```javascript
function sayHello() {
[Link]("Hello!");
sayHello(); // Logs: Hello!
```
**Hints**:
- Name functions clearly, e.g., `calculateSum` not `f`.
- Call functions after defining them.
**Additional Notes**:
- Functions reduce repetition and organize code.
- Can be called multiple times with different results.
**Exercise 1**: Write a function that logs “Good morning!”.
**Exercise 2**: Call a function that logs “Learning is fun!” twice.
**Solutions**:
1. ```javascript
function goodMorning() {
[Link]("Good morning!");
}
goodMorning();
```
2. ```javascript
function funLearning() {
[Link]("Learning is fun!");
funLearning();
funLearning();
```
---
### Parameters and Return Values
**Explanation**: Parameters accept inputs; `return` sends back output.
**Example**:
```javascript
function add(a, b) {
return a + b;
[Link](add(2, 3)); // 5
```
**Hints**:
- Parameters act like variables inside the function.
- Without `return`, functions return `undefined`.
**Additional Notes**:
- Use default parameters for optional inputs, e.g., `function greet(name =
"Guest")`.
- Only one value can be returned, but it can be an array or object.
**Exercise 1**: Write a function that takes a name and returns “Hello,
[name]!”.
**Exercise 2**: Write a function that returns the product of two numbers.
**Solutions**:
1. ```javascript
function greet(name) {
return "Hello, " + name + "!";
[Link](greet("Alice")); // Hello, Alice!
```
2. ```javascript
function multiply(a, b) {
return a * b;
[Link](multiply(4, 5)); // 20
```
---
### Arrow Functions
**Explanation**: Shorter syntax: `const name = () => { code }`. Great for
simple functions.
**Example**:
```javascript
const square = num => num * num;
[Link](square(4)); // 16
```
**Hints**:
- Omit `{}` and `return` for one-line functions.
- Use parentheses for multiple parameters, e.g., `(a, b) => a + b`.
**Additional Notes**:
- Introduced in ES6 (2015).
- No `this` binding, useful for callbacks (covered later).
**Exercise 1**: Write an arrow function to double a number.
**Exercise 2**: Write an arrow function to return “Hi, [name]!”.
**Solutions**:
1. ```javascript
const double = num => num * 2;
[Link](double(5)); // 10
```
2. ```javascript
const sayHi = name => "Hi, " + name + "!";
[Link](sayHi("Bob")); // Hi, Bob!
```
---
## 7. Arrays
### Creating Arrays
**Explanation**: Arrays store ordered lists: `let arr = [1, 2, 3]`.
**Example**:
```javascript
let numbers = [1, 2, 3, 4];
[Link](numbers); // [1, 2, 3, 4]
```
**Hints**:
- Use `const` for arrays if you won’t reassign the array itself.
- Arrays can hold any type, e.g., `[1, "text", true]`.
**Additional Notes**:
- Arrays start at index 0 (first element is `arr[0]`).
- Use `[Link]` to get the number of elements.
**Exercise 1**: Create an array of 3 colors and log it.
**Exercise 2**: Create an array with mixed types (number, string, boolean)
and log it.
**Solutions**:
1. ```javascript
let colors = ["red", "blue", "green"];
[Link](colors);
```
2. ```javascript
let mixed = [10, "hello", true];
[Link](mixed);
```
---
### Accessing Items
**Explanation**: Use index to get elements: `arr[0]` for the first item.
**Example**:
```javascript
let fruits = ["apple", "banana", "orange"];
[Link](fruits[0]); // apple
[Link](fruits[2]); // orange
```
**Hints**:
- Invalid indices (e.g., `arr[10]` in a 3-item array) return `undefined`.
- You can change elements, e.g., `fruits[0] = "pear"`.
**Additional Notes**:
- Arrays are mutable; you can update elements anytime.
- Use `[Link] - 1` for the last index.
**Exercise 1**: Access the second item in `["cat", "dog", "bird"]`.
**Exercise 2**: Change the first item in `["pen", "pencil"]` to “marker”.
**Solutions**:
1. ```javascript
let animals = ["cat", "dog", "bird"];
[Link](animals[1]); // dog
```
2. ```javascript
let items = ["pen", "pencil"];
items[0] = "marker";
[Link](items); // ["marker", "pencil"]
```
---
### Looping Through Arrays
**Explanation**: Use `for`, `while`, or `forEach` to process array elements.
**Example**:
```javascript
let fruits = ["apple", "banana", "orange"];
[Link](item => [Link](item)); // Logs each fruit
```
**Hints**:
- `forEach` is simple but doesn’t allow `break` or `continue`.
- Use `for (let i = 0; i < [Link]; i++)` for more control.
**Additional Notes**:
- `for...of` is another way: `for (let item of arr)`.
- Avoid modifying arrays while looping to prevent bugs.
**Exercise 1**: Log each item in `["a", "b", "c"]` using a `for` loop.
**Exercise 2**: Use `forEach` to log “Fruit: [item]” for `["apple", "pear"]`.
**Solutions**:
1. ```javascript
let letters = ["a", "b", "c"];
for (let i = 0; i < [Link]; i++) {
[Link](letters[i]);
```
2. ```javascript
let fruits = ["apple", "pear"];
[Link](item => [Link]("Fruit: " + item));
```
---
### Array Methods: `slice`
**Explanation**: `slice(start, end)` returns a new array with elements from
`start` to `end-1`, without modifying the original array.
**Example**:
```javascript
let arr = [3, 4, 5, 6, 2];
let sliced = [Link](1, 4); // From index 1 to 3
[Link](sliced); // [4, 5, 6]
[Link](arr); // [3, 4, 5, 6, 2] (unchanged)
```
**Hints**:
- `end` is exclusive, so `slice(1, 4)` includes indices 1, 2, 3.
- Use negative indices to count from the end, e.g., `slice(-2)` gets the last
two elements.
**Additional Notes**:
- `slice` doesn’t change the original array, unlike `splice`.
- If no `end` is given, it slices to the end, e.g., `slice(2)`.
**Exercise 1**: Slice the first 3 elements from `["a", "b", "c", "d"]`.
**Exercise 2**: Slice the last 2 elements from `[1, 2, 3, 4, 5]`.
**Solutions**:
1. ```javascript
let arr = ["a", "b", "c", "d"];
let result = [Link](0, 3);
[Link](result); // ["a", "b", "c"]
```
2. ```javascript
let arr = [1, 2, 3, 4, 5];
let result = [Link](-2);
[Link](result); // [4, 5]
```
---
### Array Methods: `splice`
**Explanation**: `splice(start, deleteCount, ...items)` removes or adds
elements at `start`, modifying the original array. Returns removed elements.
**Example**:
```javascript
let arr = [3, 4, 5, 6, 2];
let removed = [Link](1, 2, "new"); // Remove 2 items at index 1, add
"new"
[Link](arr); // [3, "new", 6, 2]
[Link](removed); // [4, 5]
```
**Hints**:
- `deleteCount` is how many items to remove; set to 0 to only add.
- `splice` changes the original array, so use carefully.
**Additional Notes**:
- Use `splice(0, [Link])` to clear an array.
- Can add multiple items, e.g., `splice(1, 0, "a", "b")`.
**Exercise 1**: Remove 2 items from index 1 in `["x", "y", "z", "w"]` and add
“new”.
**Exercise 2**: Add “middle” at index 2 in `[1, 2, 3]` without removing
anything.
**Solutions**:
1. ```javascript
let arr = ["x", "y", "z", "w"];
[Link](1, 2, "new");
[Link](arr); // ["x", "new", "w"]
```
2. ```javascript
let arr = [1, 2, 3];
[Link](2, 0, "middle");
[Link](arr); // [1, 2, "middle", 3]
```
---
### Array Methods: `push`
**Explanation**: `push(...items)` adds items to the end of an array and
returns the new length.
**Example**:
```javascript
let arr = [1, 2, 3];
let newLength = [Link](4, 5);
[Link](arr); // [1, 2, 3, 4, 5]
[Link](newLength); // 5
```
**Hints**:
- Use for quick additions to the end.
- Can add multiple items at once.
**Additional Notes**:
- Modifies the original array.
- Common for building lists dynamically.
**Exercise 1**: Add “orange” to `["apple", "banana"]`.
**Exercise 2**: Add 10 and 20 to `[1, 2, 3]` and log the new length.
**Solutions**:
1. ```javascript
let fruits = ["apple", "banana"];
[Link]("orange");
[Link](fruits); // ["apple", "banana", "orange"]
```
2. ```javascript
let nums = [1, 2, 3];
let length = [Link](10, 20);
[Link](nums); // [1, 2, 3, 10, 20]
[Link](length); // 5
```
---
### Array Methods: `pop`
**Explanation**: `pop()` removes the last element and returns it.
**Example**:
```javascript
let arr = [1, 2, 3];
let removed = [Link]();
[Link](arr); // [1, 2]
[Link](removed); // 3
```
**Hints**:
- Returns `undefined` if the array is empty.
- Use for stack-like behavior (last in, first out).
**Additional Notes**:
- Modifies the original array.
- Fast way to remove the last item.
**Exercise 1**: Remove the last item from `["cat", "dog", "bird"]`.
**Exercise 2**: Pop from `[1]` and log the removed item.
**Solutions**:
1. ```javascript
let animals = ["cat", "dog", "bird"];
[Link]();
[Link](animals); // ["cat", "dog"]
```
2. ```javascript
let nums = [1];
let removed = [Link]();
[Link](removed); // 1
```
---
### Array Methods: `shift`
**Explanation**: `shift()` removes the first element and returns it.
**Example**:
```javascript
let arr = [1, 2, 3];
let removed = [Link]();
[Link](arr); // [2, 3]
[Link](removed); // 1
```
**Hints**:
- Shifts all elements down, so index 1 becomes 0.
- Returns `undefined` for empty arrays.
**Additional Notes**:
- Modifies the original array.
- Use for queue-like behavior (first in, first out).
**Exercise 1**: Remove the first item from `["red", "blue", "green"]`.
**Exercise 2**: Shift from `[10, 20]` and log the result.
**Solutions**:
1. ```javascript
let colors = ["red", "blue", "green"];
[Link]();
[Link](colors); // ["blue", "green"]
```
2. ```javascript
let nums = [10, 20];
let removed = [Link]();
[Link](removed); // 10
```
---
### Array Methods: `unshift`
**Explanation**: `unshift(...items)` adds items to the start and returns the
new length.
**Example**:
```javascript
let arr = [1, 2, 3];
let newLength = [Link](0);
[Link](arr); // [0, 1, 2, 3]
[Link](newLength); // 4
```
**Hints**:
- Shifts existing elements up to make room.
- Can add multiple items.
**Additional Notes**:
- Modifies the original array.
- Opposite of `shift`.
**Exercise 1**: Add “first” to the start of `["second", "third"]`.
**Exercise 2**: Add 5 and 6 to the start of `[7, 8]`.
**Solutions**:
1. ```javascript
let items = ["second", "third"];
[Link]("first");
[Link](items); // ["first", "second", "third"]
```
2. ```javascript
let nums = [7, 8];
let length = [Link](5, 6);
[Link](nums); // [5, 6, 7, 8]
[Link](length); // 4
```
---
### Array Methods: `length`
**Explanation**: `[Link]` returns the number of elements. Can also set
the length to truncate or expand the array.
**Example**:
```javascript
let arr = [1, 2, 3, 4];
[Link]([Link]); // 4
[Link] = 2; // Truncate
[Link](arr); // [1, 2]
```
**Hints**:
- Setting `length` to 0 clears the array.
- Expanding `length` adds `undefined` elements.
**Additional Notes**:
- Not a method but a property.
- Useful in loops or to check array size.
**Exercise 1**: Log the length of `["a", "b", "c"]`.
**Exercise 2**: Set the length of `[1, 2, 3, 4, 5]` to 3 and log the array.
**Solutions**:
1. ```javascript
let arr = ["a", "b", "c"];
[Link]([Link]); // 3
```
2. ```javascript
let arr = [1, 2, 3, 4, 5];
[Link] = 3;
[Link](arr); // [1, 2, 3]
```
---
## 8. Objects
### Creating and Accessing Objects
**Explanation**: Objects store key-value pairs: `let obj = { key: value }`.
Access with `[Link]` or `obj["key"]`.
**Example**:
```javascript
let person = { name: "Alice", age: 25 };
[Link]([Link]); // Alice
[Link](person["age"]); // 25
```
**Hints**:
- Use descriptive keys, e.g., `userName` not `n`.
- Check if a key exists with `[Link] !== undefined`.
**Additional Notes**:
- Objects represent real-world things, like a car or person.
- Keys are usually strings, but values can be any type.
**Exercise 1**: Create an object for a book with title and author, and log the
title.
**Exercise 2**: Access the year from `{ name: "Car", year: 2020 }`.
**Solutions**:
1. ```javascript
let book = { title: "JavaScript Basics", author: "John" };
[Link]([Link]); // JavaScript Basics
```
2. ```javascript
let car = { name: "Car", year: 2020 };
[Link](car["year"]); // 2020
```
---
### Dot vs Bracket Notation
**Explanation**:
- **Dot**: `[Link]` for known, valid keys.
- **Bracket**: `obj["key"]` for dynamic or special keys.
**Example**:
```javascript
let obj = { firstName: "Bob", "last name": "Smith" };
[Link]([Link]); // Bob
[Link](obj["last name"]); // Smith
```
**Hints**:
- Use dot for simple keys, bracket for keys with spaces or variables.
- Dot notation fails for keys like `obj.123` or `[Link] name`.
**Additional Notes**:
- Bracket notation is more flexible, e.g., `obj[someVariable]`.
- Dot notation is cleaner and more common.
**Exercise 1**: Access a key with a space, e.g., `city name` from an object.
**Exercise 2**: Use a variable to access a key in `{ color: "blue" }`.
**Solutions**:
1. ```javascript
let obj = { "city name": "Lagos" };
[Link](obj["city name"]); // Lagos
```
2. ```javascript
let obj = { color: "blue" };
let key = "color";
[Link](obj[key]); // blue
```
---
### Nested Objects
**Explanation**: Objects can contain objects, e.g., `{ person: { name: "Alice"
} }`. Access with chained dots or brackets.
**Example**:
```javascript
let student = { name: "Alice", details: { age: 20, grade: "A" } };
[Link]([Link]); // 20
```
**Hints**:
- Check for nested objects before accessing, e.g., `[Link]?.age`.
- Use clear key names to avoid confusion.
**Additional Notes**:
- Useful for complex data, like a user with address and preferences.
- Can nest arrays or other types too.
**Exercise 1**: Access the city from `{ user: { name: "Bob", address: { city:
"Lagos" } } }`.
**Exercise 2**: Create a nested object for a car with model and specs (e.g.,
year, color).
**Solutions**:
1. ```javascript
let obj = { user: { name: "Bob", address: { city: "Lagos" } } };
[Link]([Link]); // Lagos
```
2. ```javascript
let car = { model: "Toyota", specs: { year: 2021, color: "red" } };
[Link]([Link]); // red
```
---
## 9. DOM Manipulation (Basic)
### `[Link]()`
**Explanation**: Selects an HTML element by its ID:
`[Link]("myId")`.
**Example**:
```html
<p id="myPara">Hello</p>
<script>
let para = [Link]("myPara");
[Link]([Link]); // Hello
</script>
```
**Hints**:
- Ensure the ID exists in the HTML.
- IDs are unique; only one element per ID.
**Additional Notes**:
- Part of the DOM (Document Object Model), which represents the webpage.
- Fast and specific for targeting elements.
**Exercise 1**: Select an element with ID “title” and log its text.
**Exercise 2**: Change the text of an element with ID “greeting” to “Hi!”.
**Solutions**:
1. ```html
<h1 id="title">Welcome</h1>
<script>
let title = [Link]("title");
[Link]([Link]); // Welcome
</script>
```
2. ```html
<p id="greeting">Hello</p>
<script>
let greeting = [Link]("greeting");
[Link] = "Hi!";
</script>
```
---
### `innerHTML`, `style`, `value`
**Explanation**:
- `innerHTML`: Sets/gets HTML content.
- `style`: Changes CSS, e.g., `[Link]`.
- `value`: Gets/sets input field values.
**Example**:
```html
<p id="text">Old text</p>
<input id="input" value="Type here">
<script>
let text = [Link]("text");
[Link] = "<b>New text</b>";
[Link] = "blue";
let input = [Link]("input");
[Link]([Link]); // Type here
</script>
```
**Hints**:
- Use `textContent` for plain text to avoid security risks with `innerHTML`.
- `style` changes are inline; CSS classes are better for big changes.
**Additional Notes**:
- `innerHTML` can run scripts, so sanitize user input.
- `style` properties use camelCase, e.g., `backgroundColor` not
`background-color`.
**Exercise 1**: Change the `innerHTML` of a `<div>` to “Bold!” with bold
tags.
**Exercise 2**: Set an input’s value to “JavaScript” and change its text color
to red.
**Solutions**:
1. ```html
<div id="myDiv">Text</div>
<script>
let div = [Link]("myDiv");
[Link] = "<b>Bold!</b>";
</script>
```
2. ```html
<input id="myInput">
<script>
let input = [Link]("myInput");
[Link] = "JavaScript";
[Link] = "red";
</script>
```
---
### `addEventListener()`
**Explanation**: Attaches a function to an event:
`[Link]("event", () => { code })`.
**Example**:
```html
<button id="btn">Click</button>
<script>
let btn = [Link]("btn");
[Link]("click", () => {
[Link]("Button clicked!");
});
</script>
```
**Hints**:
- Use event names like `"click"`, `"change"`, etc.
- The function runs when the event happens.
**Additional Notes**:
- More flexible than `onclick` attributes.
- The event object (`event`) gives details, e.g., `[Link]`.
**Exercise 1**: Add a click listener to a button that logs “Clicked!”.
**Exercise 2**: Change a `<p>`’s text to “Done” when a button is clicked.
**Solutions**:
1. ```html
<button id="btn">Click</button>
<script>
let btn = [Link]("btn");
[Link]("click", () => {
[Link]("Clicked!");
});
</script>
```
2. ```html
<button id="btn">Click</button>
<p id="text">Waiting</p>
<script>
let btn = [Link]("btn");
let text = [Link]("text");
[Link]("click", () => {
[Link] = "Done";
});
</script>
```
---
## 10. Events
### Common Events: `onclick`, `onchange`, `onmouseover`
**Explanation**:
- `onclick`: Runs on click.
- `onchange`: Runs when an input changes.
- `onmouseover`: Runs when the mouse hovers.
**Example**:
```html
<input id="input" type="text">
<script>
let input = [Link]("input");
[Link] = () => [Link]("Input changed!");
</script>
```
**Hints**:
- Use `addEventListener` instead of `onchange` for flexibility.
- Test events in the browser to see them work.
**Additional Notes**:
- Events make websites interactive.
- Avoid inline events like `<button onclick="...">`.
**Exercise 1**: Log “Hovered!” on `onmouseover` for a `<div>`.
**Exercise 2**: Log the value of an input on `onchange`.
**Solutions**:
1. ```html
<div id="myDiv">Hover me</div>
<script>
let div = [Link]("myDiv");
[Link] = () => [Link]("Hovered!");
</script>
```
2. ```html
<input id="input" type="text">
<script>
let input = [Link]("input");
[Link] = () => [Link]([Link]);
</script>
```
---
### Event Listeners
**Explanation**: `addEventListener` binds functions to events, allowing
dynamic responses.
**Example**:
```html
<button id="btn">Click</button>
<script>
let btn = [Link]("btn");
[Link]("click", event => {
[Link]("Clicked on", [Link]);
});
</script>
```
**Hints**:
- Use `[Link]()` for forms to stop default actions.
- Log `event` to see its properties.
**Additional Notes**:
- Can add multiple listeners to one element.
- Remove with `removeEventListener` if needed.
**Exercise 1**: Add a click listener to log “Button pressed!”.
**Exercise 2**: Prevent a form submission and log the input value.
**Solutions**:
1. ```html
<button id="btn">Press</button>
<script>
let btn = [Link]("btn");
[Link]("click", () => {
[Link]("Button pressed!");
});
</script>
```
2. ```html
<form id="form"><input id="input" type="text"><button
type="submit">Submit</button></form>
<script>
let form = [Link]("form");
let input = [Link]("input");
[Link]("submit", event => {
[Link]();
[Link]([Link]);
});
</script>
```
---
## 11. Project Ideas for Practice
These projects help you apply what you’ve learned. Try at least one!
### Calculator
- **Goal**: Build a web calculator for addition, subtraction, multiplication,
division.
- **Steps**: Create an HTML form with inputs for two numbers and buttons
for operations. Use JavaScript to calculate and display results.
- **Example**:
```html
<input id="num1" type="number">
<input id="num2" type="number">
<button id="add">Add</button>
<p id="result"></p>
<script>
let num1 = [Link]("num1");
let num2 = [Link]("num2");
let add = [Link]("add");
let result = [Link]("result");
[Link]("click", () => {
let sum = Number([Link]) + Number([Link]);
[Link] = sum;
});
</script>
```
### To-do List
- **Goal**: Create a list where users add and remove tasks.
- **Steps**: Use an input for tasks, a button to add, and a list to display. Add
remove buttons for each task.
- **Example**:
```html
<input id="task" placeholder="Enter task">
<button id="add">Add</button>
<ul id="list"></ul>
<script>
let task = [Link]("task");
let add = [Link]("add");
let list = [Link]("list");
[Link]("click", () => {
let li = [Link]("li");
[Link] = [Link];
[Link](li);
[Link] = "";
});
</script>
```
### Quiz App
- **Goal**: Build a quiz with multiple-choice questions.
- **Steps**: Store questions in an array of objects, display one at a time,
track score, and show results.
- **Example**:
```html
<p id="question"></p>
<button id="ans1"></button>
<script>
let question = [Link]("question");
let ans1 = [Link]("ans1");
let quiz = [{ q: "2+2?", a: "4", correct: true }];
[Link] = quiz[0].q;
[Link] = quiz[0].a;
[Link]("click", () => alert("Correct!"));
</script>
```
### Student Grade Tracker
- **Goal**: Track student grades and calculate averages.
- **Steps**: Use a form to input student name and grades, store in an array
of objects, display in a table.
- **Example**:
```html
<input id="name" placeholder="Name">
<input id="grade" type="number">
<button id="add">Add</button>
<div id="table"></div>
<script>
let students = [];
let name = [Link]("name");
let grade = [Link]("grade");
let add = [Link]("add");
let table = [Link]("table");
[Link]("click", () => {
[Link]({ name: [Link], grade: Number([Link]) });
[Link] = [Link](students);
});
</script>
```
### Light/Dark Theme Switcher
- **Goal**: Toggle between light and dark themes.
- **Steps**: Add a button to switch CSS styles or classes for the page.
- **Example**:
```html
<button id="toggle">Toggle Theme</button>
<script>
let toggle = [Link]("toggle");
[Link]("click", () => {
[Link] =
[Link] === "black" ? "white" : "black";
[Link] = [Link] === "white" ?
"black" : "white";
});
</script>