JavaScript Topics
Day 15 :
- Spread
- Rest
- De-structuring
Spread:
// 1. Array
let array1 = [1, 2, 3, 4];
let array2 = [...array1, 5, 6, 7];
let array3 = [...array2, 8, 9, 10];
// console.log(array2);
// console.log(array3)
// 2. Object
let Object1 = { a: 1, b: 2 };
let object2 = { ...Object1, c: 3, d: 4 };
let object3 = { ...object2, e: 5, f: 6 };
// console.log(object2);
// console.log(object3);
// 3. function
function sum(a, b, c, d) {
return a + b + c + d;
}
let numbers = [1, 2, 3, 4];
// console.log(sum(...numbers))
Rest:
function addingNumbers(...numbers) {
// console.log(numbers)
let total =0;
for(let i=0; i<numbers.length; i++){
total = total + numbers[i]
}
return total
}
console.log(addingNumbers(...array3));
De-structuring:
// 1. Object
let Student = {
name: "Hema",
role: "Developer",
username: "Hema_H",
email: "hema@example.com",
};
// console.log(Student.name)
// console.log(Student.role)
let { name, role: task, ...otherDetails } = Student;
// console.log(name)
// console.log(role)
// console.log(task);
// console.log(otherDetails)
// 2. Array
let number = [1,2,3,4,5,6,7,8,9]
// console.log(number[1])
// console.log(number[2])
let [first, second, third, ...remaingNumbers] = number;
console.log(first)
console.log(third)
console.log(remaingNumbers)
Tasks:
Spread:
1. Copying Arrays with Modifications:
Given an array of numbers, create a function that makes a copy of the array and then adds a new number to the end of the copied array using the spread operator.
2. Combining Objects with Defaults:
Write a function that accepts an object and merges it with a default object, providing default values for missing keys using the spread operator.
Rest:
3. Calculating Average:
Write a function that calculates the average of a variable number of arguments passed using the rest parameter.
De-structuring:
4. Extract Specific Values:
Write a function that accepts an array containing a person's name, age, and country, and uses destructuring to extract these values into separate variables.
5. Alias Object Properties:
Given an object with properties firstName and lastName, use destructuring to extract these properties into variables named first and last.
Interview Questions:
1. What is the purpose of the spread operator in JavaScript? Provide examples of its usage in arrays and objects?
2. Explain a situation where rest parameters are advantageous compared to using the arguments object?
3. What is destructuring in JavaScript, and what benefits does it offer when working with arrays and objects?
4. Discuss the differences between using the spread operator for objects and arrays?
No comments:
Post a Comment