JS Exam 4: Arrays, Objects, and ES6+ (10 mixed exercises)
JS Exam 4: Advanced Arrays and Objects
Test your ES6+ skills, including advanced data handling and concise function syntax.
Exercise 1
Arrow Functions
Convert the following function to an arrow function:
- Function: `function add(a, b) { return a + b; }`
- Write it as `const add = ...`
- Shorten it to a single-line implicit return.
Solution
const add = (a, b) => a + b;
Exercise 2
Map
You have an array `[1, 2, 3]`:
- Use `map` to create a new array of squares (each number times itself).
- Expected result: `[1, 4, 9]`.
Solution
const numbers = [1, 2, 3];
const squared = numbers.map(num => num * num);
console.log(squared);
Exercise 3
Filter
You have an ages array `[15, 22, 18, 10, 30]`:
- Use `filter` to create a new array with adults only (>= 18).
Solution
const ages = [15, 22, 18, 10, 30];
const adults = ages.filter(age => age >= 18);
console.log(adults); // [22, 18, 30]
Exercise 4
Object Destructuring
You have `user = { name: "Ali", email: "ali@test.com" }`:
- Extract `name` and `email` into separate variables.
- Log the new variables.
Solution
const user = { name: "Ali", email: "ali@test.com" };
const { name, email } = user;
console.log(name, email);
Exercise 5
Spread Operator
Merge two arrays:
- First array `arr1 = [1, 2]`.
- Second array `arr2 = [3, 4]`.
- Create `arr3` combining both using `...` (spread).
Solution
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4]
Exercise 6
Find
Find an item in an array of objects:
- You have `users = [{id: 1, name: "A"}, {id: 2, name: "B"}]`.
- Use `find` to get the user with `id` 2.
Solution
const users = [{id: 1, name: "A"}, {id: 2, name: "B"}];
const user = users.find(u => u.id === 2);
console.log(user); // {id: 2, name: "B"}
Exercise 7
Default Parameters
Create a greeting function:
- `greet(name)` prints "Hello, [name]".
- Give `name` a default value of "Guest" if not provided.
- Call the function without arguments.
Solution
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
greet(); // Hello, Guest
Exercise 8
Reduce
Calculate the sum of numbers:
- You have `prices = [10, 20, 30]`.
- Use `reduce` to calculate the total sum.
Solution
const prices = [10, 20, 30];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 60
Exercise 9
Array Destructuring
Extract values from an array:
- You have `coords = [10, 20]`.
- Extract the values into `x` and `y` using destructuring.
Solution
const coords = [10, 20];
const [x, y] = coords;
console.log(x, y);
Exercise 10
Enhanced Object Literals
Create an object using shorthand:
- You have `name = "Sara"` and `age = 25`.
- Create `person` without repeating property names (shorthand properties).
Solution
const name = "Sara";
const age = 25;
const person = { name, age }; // instead of { name: name, age: age }
console.log(person);