Q19.
Explain reduce(), map(), forEach() and filter() methods in JavaScript:
1. forEach(): Executes a function on each array element. It does not return a new array.
Example:
numbers.forEach(num => console.log(num)); // logs each number
2. map(): Transforms each element and returns a new array.
Example:
let doubled = numbers.map(num => num * 2); // [2, 4, 6, 8]
3. filter(): Returns a new array of only elements that pass a test.
Example:
let even = numbers.filter(num => num % 2 === 0); // [2, 4]
4. reduce(): Reduces the array to a single value.
Example:
let sum = numbers.reduce((acc, val) => acc + val, 0); // 10
Q20. Explain unshift(), splice(), slice(), push() and pop() methods in JavaScript:
1. unshift(): Adds one or more elements to the beginning of an array.
Example: arr.unshift(0);
2. push(): Adds one or more elements to the end of an array.
Example: arr.push(5);
3. pop(): Removes the last element of an array.
Example: arr.pop();
4. splice(): Adds/removes elements from any position in the array.
Example: arr.splice(2, 1); // removes 1 item at index 2
5. slice(): Extracts a portion of array into a new array.
Example: arr.slice(1, 3); // gets elements from index 1 to 2