DEV Community

avinash-repo
avinash-repo

Posted on

Top uses

Certainly! Here's an example of JavaScript code written using ES6 features:
https://onecompiler.com/javascript/423nr975c


const users1 = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'David' }
];

const filet=users1.filter(item=>item.id>2 && item.name=='David')
console.log("Line:",filet)

// Using arrow functions and template literals
const greet = (name) => `Hello, ${name}!`;

console.log(greet("Alice")); // Output: Hello, Alice!

// Using destructuring
const person = { name: "Bob", age: 30, country: "USA" };
const { name, age } = person;

console.log(`Name: ${name}, Age: ${age}`); // Output: Name: Bob, Age: 30

// Using spread operator
const numbers = [1, 2, 3, 4, 5];
const sum = (a, b, c, d, e) => a + b + c + d + e;

console.log(sum(...numbers)); // Output: 15

// Using classes
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.
Enter fullscreen mode Exit fullscreen mode

In this example:

  • Arrow functions (greet) provide a concise syntax for defining functions.
  • Template literals are used for string interpolation in the greet function.
  • Destructuring is used to extract values from objects (person) into variables (name, age).
  • The spread operator (...) is used to pass elements of an array (numbers) as individual arguments to the sum function.
  • Classes (Animal, Dog) provide a more structured way to define object blueprints, along with inheritance using the extends keyword.

Certainly! Here are five complex examples demonstrating the use of destructuring in JavaScript ES6:

  1. Nested Destructuring:
const person = {
  name: "Alice",
  age: 30,
  address: {
    city: "New York",
    country: "USA"
  }
};

const { name, age, address: { city, country } } = person;

console.log(name);    // Output: Alice
console.log(city);    // Output: New York
console.log(country); // Output: USA
Enter fullscreen mode Exit fullscreen mode
  1. Destructuring Function Parameters:
const printPersonInfo = ({ name, age, address: { city, country } }) => {
  console.log(`Name: ${name}, Age: ${age}, City: ${city}, Country: ${country}`);
};

printPersonInfo(person);
// Output: Name: Alice, Age: 30, City: New York, Country: USA
Enter fullscreen mode Exit fullscreen mode
  1. Skipping Elements:
const numbers = [1, 2, 3, 4, 5];

const [, second, , fourth] = numbers;

console.log(second);  // Output: 2
console.log(fourth);  // Output: 4
Enter fullscreen mode Exit fullscreen mode
  1. Rest Pattern:
const [first, ...rest] = numbers;

console.log(first); // Output: 1
console.log(rest);  // Output: [2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode
  1. Destructuring with Default Values:
const settings = { color: "blue", fontSize: 14 };

const { color, fontSize, fontWeight = "normal" } = settings;

console.log(color);      // Output: blue
console.log(fontSize);   // Output: 14
console.log(fontWeight); // Output: normal
Enter fullscreen mode Exit fullscreen mode

These examples illustrate various scenarios where destructuring can be used, including nested objects, function parameters, skipping elements, using rest patterns, and providing default values. Destructuring is a powerful feature that helps in extracting values from objects and arrays concisely.

Certainly! Here are five tricky examples demonstrating the usage of the map() method in JavaScript:

  1. Mapping an Array of Objects:
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

const userIds = users.map(user => user.id);

console.log(userIds); // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
  1. Mapping with Index:
const words = ['apple', 'banana', 'cherry'];

const wordWithIndex = words.map((word, index) => `${word}-${index}`);

console.log(wordWithIndex); // Output: ['apple-0', 'banana-1', 'cherry-2']
Enter fullscreen mode Exit fullscreen mode
  1. Mapping with Array Method:
const numbers = [1, 2, 3, 4, 5];

const evenSquares = numbers.map(num => num ** 2).filter(square => square % 2 === 0);

console.log(evenSquares); // Output: [4, 16]
Enter fullscreen mode Exit fullscreen mode
  1. Mapping an Array of Functions:
const operations = [
  num => num * 2,
  num => num + 3,
  num => num - 1
];

const result = operations.map(operation => operation(5));

console.log(result); // Output: [10, 8, 4]
Enter fullscreen mode Exit fullscreen mode
  1. Mapping with Conditional Logic:
const numbers = [1, 2, 3, 4, 5];

const evenOrOdd = numbers.map(num => num % 2 === 0 ? 'even' : 'odd');

console.log(evenOrOdd); // Output: ['odd', 'even', 'odd', 'even', 'odd']
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate various scenarios where the map() method can be used creatively, including mapping array of objects, using index, combining with other array methods, mapping array of functions, and mapping with conditional logic.

Certainly! Let's consider a real-world scenario where the map() method can be used effectively.

Scenario: Calculating Total Prices with Tax

Suppose you have an array of items in a shopping cart, where each item is represented by an object with properties like name, price, and quantity. You need to calculate the total price for each item including tax and generate a receipt.

const shoppingCart = [
  { name: 'Laptop', price: 1000, quantity: 1 },
  { name: 'Mouse', price: 20, quantity: 2 },
  { name: 'Keyboard', price: 50, quantity: 1 }
];

const taxRate = 0.1; // 10% tax rate

// Function to calculate total price for an item including tax
const calculateTotalPrice = (item) => {
  const totalPrice = item.price * item.quantity;
  const tax = totalPrice * taxRate;
  return totalPrice + tax;
};

// Using map() to calculate total price including tax for each item
const receipt = shoppingCart.map(item => {
  const totalPrice = calculateTotalPrice(item);
  return {
    name: item.name,
    totalPrice: totalPrice.toFixed(2)
  };
});

console.log(receipt);
Enter fullscreen mode Exit fullscreen mode

In this scenario:

  • We have an array shoppingCart containing items in the cart, each represented by an object with name, price, and quantity.
  • We define a function calculateTotalPrice() to calculate the total price including tax for each item.
  • We use the map() method to iterate over each item in the shoppingCart, calculate the total price including tax for each item using calculateTotalPrice(), and create a new object for each item in the receipt array containing the item name and its total price.
  • Finally, we log the receipt array to the console, which contains the calculated total price including tax for each item in the shopping cart.

This real-world scenario showcases how the map() method can be used to transform data and perform calculations efficiently in JavaScript.

If you want to destructure both id and name from each object in the users array while using the map() method, you can do it like this:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'David' }
];

// Using map() to destructure both id and name from each object
const userIdsAndNames = users.map(({ id, name }) => ({ id, name }));

console.log(userIdsAndNames);
Enter fullscreen mode Exit fullscreen mode

In this code:

  • We use the map() method to iterate over each object in the users array.
  • For each object, we destructure the id and name properties directly in the parameter of the arrow function passed to map().
  • We then return a new object containing both id and name.
  • The resulting array userIdsAndNames contains objects with only the id and name properties extracted from each object in the users array.

The output will be an array of objects with only id and name properties extracted from each user object in the original users array.

The filter() method is primarily used for filtering elements from an array based on a condition. It does not inherently involve destructuring elements of an array. However, if you intend to use filter() to achieve a similar result as map() but only with certain conditions, you can still destructure elements within the filtering function. Here's how you can do it:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'David' }
];

// Using filter() to destructure both id and name from each object
const userIdsAndNames = users.filter(({ id, name }) => {
  // Here, we can perform any condition based on id, name, or both
  return id % 2 === 0; // Filter users with even id
}).map(({ id, name }) => ({ id, name }));

console.log(userIdsAndNames);
Enter fullscreen mode Exit fullscreen mode

In this code:

  • We use the filter() method to filter elements of the users array based on a condition.
  • Inside the filter function, we destructure the id and name properties directly in the parameter of the arrow function.
  • We can then apply any filtering condition based on id, name, or both.
  • After filtering, we use the map() method to destructure id and name properties again to extract them into a new array.
  • The resulting array userIdsAndNames contains objects with only the id and name properties extracted from each user object that meets the filtering condition.

This approach combines filter() and map() to achieve the desired result of filtering and destructuring elements of the array.

The provided code snippet performs operations on an array of user objects. Let's analyze each part individually:

  1. Declaration of the users array containing objects with id and name properties.
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
  { id: 4, name: 'David' }
];
Enter fullscreen mode Exit fullscreen mode
  1. Utilization of the map() method to create an array of strings combining the name and id of each user.
const userIdsAndNames = users.map(user =>  `${user.name}-${user.id}` );
console.log(userIdsAndNames);
Enter fullscreen mode Exit fullscreen mode
  1. The second usage of map() creates an array of objects, each containing the original user object and its index in the users array.
const userIdsAndNames1 = users.map((obj, key) => ({ obj, key }));
console.log(userIdsAndNames1);
Enter fullscreen mode Exit fullscreen mode
  1. The third application of map() destructures the id and name properties from each user object and creates a new array of objects with these properties.
const userIdsAndNames2 = users.map(({ id, name }) => ({ name, id }));
console.log(userIdsAndNames2);
Enter fullscreen mode Exit fullscreen mode
  1. Finally, the last use of map() extracts only the name property from each user object.
const userIdsAndNames3 = users.map(user =>  user.name );
console.log(userIdsAndNames3);
Enter fullscreen mode Exit fullscreen mode

In summary, the provided code demonstrates various uses of the map() method to manipulate an array of user objects, including creating concatenated strings, mapping to objects with the original object and index, extracting specific properties, and obtaining an array of specific property values.

Top comments (0)