Here are JavaScript code exercises to help students understand and practice JavaScript syntax, focusing on variable declaration, conditionals, loops, and arrow functions:
### 1. Declaring Variables with `let` and `const`
#### Explanation:
- `let`: Used to declare variables whose values **can be changed**. It has block scope, meaning the variable only exists within the block where it's declared.
- `const`: Used to declare variables whose values **cannot be changed** once assigned. It also has block scope.
#### Exercise:
1. **Declare variables using `let` for mutable values**.
2. **Declare variables using `const` for immutable values**.
3. **Attempt to reassign a `const` variable and observe the error**.
#### Code Example:
```javascript
// 1. Declare a variable with `let` and change its value
let age = 25;
console.log("Initial age:", age); // Output: 25
age = 26;
console.log("Updated age:", age); // Output: 26
// 2. Declare a constant variable with `const` and try to reassign it
const birthYear = 1998;
console.log("Birth Year:", birthYear); // Output: 1998
// Uncommenting the next line will throw an error
// birthYear = 2000; // Error: Assignment to constant variable
// 3. Experimenting with scope of `let`
if (true) {
let scopedVariable = "I exist only in this block";
console.log(scopedVariable); // Output: I exist only in this block
}
// console.log(scopedVariable); // Error: scopedVariable is not defined
// 4. Using `const` for objects - you can modify object properties, but not reassign the object
const person = { name: "Alice", age: 30 };
console.log(person); // Output: { name: 'Alice', age: 30 }
person.age = 31; // Allowed: Modifying property
console.log(person); // Output: { name: 'Alice', age: 31 }
// person = { name: "Bob", age: 25 }; // Error: Assignment to constant variable
```
#### Key Points:
- `let` is for values that may change.
- `const` is for values that stay constant (with the exception of modifying properties of objects/arrays).
- Variables declared with `let` and `const` are **block-scoped**.
---
### 2. Conditionals with `if` and `else`
#### Explanation:
- Conditional statements control the flow of the program based on specific conditions. Use `if` to execute code when a condition is true, `else if` for an additional condition, and `else` for fallback code when no conditions are true.
#### Exercise:
1. Write an `if` statement that checks if a number is positive, negative, or zero.
2. Use `else if` to handle different conditions.
3. Implement a fallback with `else`.
#### Code Example:
```javascript
let number = -10;
// 1. Check if the number is positive
if (number > 0) {
console.log("The number is positive.");
}
// 2. Check if the number is negative
else if (number < 0) {
console.log("The number is negative.");
}
// 3. Handle the case where the number is zero
else {
console.log("The number is zero.");
}
// Try changing the number value to 10 or 0 and observe the output
```
#### Additional Exercise:
1. Create a grading system using `if-else` statements:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- Below 60: F
```javascript
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else if (score >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
```
#### Key Points:
- Use `if` to check conditions, `else if` for additional checks, and `else` for a fallback option.
- The program executes the first `true` condition it encounters.
---
### 3. C-Style `for` Loop
#### Explanation:
- The traditional `for` loop is a way to repeatedly execute a block of code a set number of times. It has three parts: initialization, condition, and iteration expression.
#### Exercise:
1. Write a `for` loop to print numbers from 1 to 10.
2. Modify the loop to print only even numbers between 1 and 10.
3. Use a loop to calculate the sum of numbers from 1 to 100.
#### Code Example:
```javascript
// 1. Print numbers from 1 to 10
for (let i = 1; i <= 10; i++) {
console.log(i); // Output: 1, 2, 3, ..., 10
}
// 2. Print even numbers from 1 to 10
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i); // Output: 2, 4, 6, 8, 10
}
}
// 3. Calculate the sum of numbers from 1 to 100
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log("Sum of numbers from 1 to 100:", sum); // Output: 5050
```
#### Key Points:
- The loop's structure: `for (initialization; condition; iteration)`.
- The loop runs as long as the condition is `true`.
- Update the loop variable (like `i++`) after each iteration.
---
### 4. Arrow Functions
#### Explanation:
- Arrow functions provide a **concise syntax** for writing functions in JavaScript.
- Unlike regular functions, arrow functions do not have their own `this` context, making them ideal for situations where you want to avoid binding issues (e.g., with callbacks).
#### Exercise:
1. Write an arrow function that takes two numbers and returns their sum.
2. Convert a traditional function to an arrow function.
3. Use an arrow function in an array's `map` method.
#### Code Example:
```javascript
// 1. Arrow function to return the sum of two numbers
const add = (a, b) => a + b;
console.log(add(5, 10)); // Output: 15
// 2. Traditional function vs Arrow function
// Traditional function
function multiply(a, b) {
return a * b;
}
console.log(multiply(4, 5)); // Output: 20
// Arrow function equivalent
const multiplyArrow = (a, b) => a * b;
console.log(multiplyArrow(4, 5)); // Output: 20
// 3. Use an arrow function with `map` to double the values in an array
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
// 4. Arrow function with no parameters
const greet = () => console.log("Hello, world!");
greet(); // Output: Hello, world!
```
#### Key Points:
- Arrow functions offer a shorter syntax: `const funcName = (param1, param2) => { // function body };`.
- For single-line functions, the `{}` and `return` can be omitted.
- They are ideal for callbacks and array manipulation functions like `map`, `filter`, or `reduce`.
- Arrow functions don't have their own `this`, which avoids `this` binding issues.
---
These exercises provide a strong foundation in understanding the syntax of JavaScript, covering variables, conditionals, loops, and functions. Practicing these will help students internalize these key language features.