Advance - JS Questions

  1. What is diff between map and forEach of array function.?
  2. Example of destructuring?
1 Like
  1. map it will returns a new array and forEach it does not return a new array.
2 Likes
  1. The main difference between map() and forEach() is that map() returns a new array, while forEach() does not. map() is used to transform the elements of an array, while forEach() is used to loop through the elements of an array.

  2. Destructuring is a technique that allows you to extract the values from an object or array into variables.

2 Likes
    • map() creates a new array by transforming each element of the original array and returns the new array.
  • forEach() executes a provided function for each element of the array without creating a new array or returning any value. It is primarily used for performing side effects or actions for each element.

2.// Array destructuring
const numbers = [1, 2, 3, 4];

// Destructuring assignment
const [firstNumber, secondNumber] = numbers;

console.log(firstNumber); // Output: 1
console.log(secondNumber);// Output: 2

2 Likes
  1. Map and foreach are pretty same, in map we can create a whole new array by performing a basic operation on each element, like multiply by two divide by half, the only difference is that foreach wont create a new array and doesnt return in every iteration like in map

  2. Const obj = {
    name: ‘harry’,
    age: ‘25’
    }
    let {name, age} = obj;

2 Likes
  1. map function = transforms each element of an array and returns a new array.
    forEach function = execute a callback function for each element in the array.

  2. const [a, b, c] = [1, 2, 3];
    console.log(a, b, c);

const { name, age, city } = { name: ‘sagar’, age: 23, city: ‘bhagalpur’ };
console.log(name, age, city);

2 Likes

ANS 1:- 1.forEach:- 1.The forEach() method does not returns a new array.
2.It is not executed for empty elements.
2. map:-1. The map() method returns an entirely new array.
2.It does not change the original array.
ANS 2:- Const obj = {
name: ‘taukir’,
age: ‘23’
}
let {name, age} = obj;

2 Likes

map returns new array while forEach doesn’t

2 Likes
  1. map method returns a new array and forEach does not return a new array.
    2 destructing is a method to extract values from array or string.
    Const obj = {
    name: ‘charan’,
    age: ‘22’
    }
    let {name, age} = obj;
2 Likes