< / >
Published on

ES6+ Features

ES6+ introduces powerful features like destructuring, spread/rest operators, template literals, default parameters, and Sets/Maps, enhancing JavaScript's flexibility and expressiveness for modern development needs. These additions streamline coding, enabling concise syntax and improved data manipulation and organization.

Table of Contents

Destructuring

Destructuring allows you to extract data from arrays or objects into distinct variables. This feature simplifies code and improves readability.

Example with Arrays:

const numbers = [1, 2, 3, 4, 5]
const [first, second, ...rest] = numbers
console.log(first) // Output: 1
console.log(second) // Output: 2
console.log(rest) // Output: [3, 4, 5]
// Example object with nested structure
const user = {
  id: 101,
  name: 'Rajnish Kumar',
  age: 30,
  address: {
    city: 'New Delhi',
    country: 'India',
  },
  hobbies: ['Reading', 'Traveling', 'Photography'],
}

// Destructuring nested object properties
const {
  id,
  name,
  address: { city, country },
  hobbies: [firstHobby, ...otherHobbies],
} = user

console.log(id) // Output: 101
console.log(name) // Output: Rajnish Kumar
console.log(city) // Output: New Delhi
console.log(country) // Output: India
console.log(firstHobby) // Output: Reading
console.log(otherHobbies) // Output: ['Traveling', 'Photography']
// Example array with nested structure
const data = [
  'Rajnish',
  'Kumar',
  ['Reading', 'Traveling', 'Photography'],
  { city: 'New Delhi', country: 'India' },
]

// Destructuring array elements
const [firstName, lastName, [firstHobby, ...otherHobbies], { city, country }] = data

console.log(firstName) // Output: Rajnish
console.log(lastName) // Output: Kumar
console.log(firstHobby) // Output: Reading
console.log(otherHobbies) // Output: ['Traveling', 'Photography']
console.log(city) // Output: New Delhi
console.log(country) // Output: India

Spread/rest operators

The spread operator (...) allows you to expand an iterable (like an array) into individual elements, while the rest parameter collects multiple elements into a single array.

Spread Operator Example:

const numbers = [1, 2, 3]
const newArray = [...numbers, 4, 5]
console.log(newArray) // Output: [1, 2, 3, 4, 5]
// Example function to calculate the average of numbers
const calculateAverage = (...numbers) => {
  const sum = numbers.reduce((total, num) => total + num, 0)
  return sum / numbers.length
}

// Example array of numbers
const numbers = [10, 20, 30, 40, 50]

// Calculating the average of numbers using spread operator
const average = calculateAverage(...numbers)
console.log('Average:', average) // Output: 30

// Example function to merge objects
const mergeObjects = (target, ...sources) => {
  return sources.reduce((merged, source) => {
    return {
      ...merged,
      ...source,
    }
  }, target)
}

// Example objects to merge
const obj1 = { a: 1, b: 2 }
const obj2 = { b: 3, c: 4 }
const obj3 = { d: 5 }

// Merging objects using spread operator
const mergedObject = mergeObjects({}, obj1, obj2, obj3)
console.log('Merged Object:', mergedObject)
// Output: Merged Object: { a: 1, b: 3, c: 4, d: 5 }
  • We define a function calculateAverage that takes any number of arguments using the rest parameter (...numbers). It calculates the average of these numbers.
  • We have an array numbers containing numerical values.
  • We use the spread operator ...numbers to pass the elements of the numbers array as individual arguments to the calculateAverage function.
  • We define a function mergeObjects that merges multiple objects into a single object. It takes a target object and any number of source objects using the rest parameter.
  • We have three objects obj1, obj2, and obj3.
  • We use the spread operator {...merged, ...source} within the mergeObjects function to merge the source objects into the merged object.

Rest Parameter Example:

const sum = (...args) => args.reduce((total, num) => total + num, 0)
console.log(sum(1, 2, 3, 4)) // Output: 10
// Example function to sum numbers with a variable number of arguments
const sumNumbers = (...args) => {
  return args.reduce((total, num) => total + num, 0)
}

// Using the sumNumbers function with different numbers of arguments
console.log(sumNumbers(1, 2, 3)) // Output: 6
console.log(sumNumbers(10, 20, 30, 40)) // Output: 100
console.log(sumNumbers(5)) // Output: 5
console.log(sumNumbers()) // Output: 0

Template literals

Template literals allow for easier string interpolation and multiline strings using backticks ()`.

const name = 'Rajnish'
const greeting = `Hello, ${name}!
How are you today?`
console.log(greeting)
// Output:
// Hello, Rajnish!
// How are you today?

Default parameters

Default parameters allow you to assign default values to function parameters if they are not explicitly passed when the function is called.

const greet = (name = 'Guest') => {
  console.log(`Hello, ${name}!`)
}
greet() // Output: Hello, Guest!
greet('Rajnish') // Output: Hello, Rajnish!

Sets and Maps

Sets are collections of unique values, while Maps are collections of key-value pairs. They provide efficient data storage and retrieval.

Set Example:

const uniqueNumbers = new Set([1, 2, 3, 1, 2])
console.log(uniqueNumbers) // Output: Set { 1, 2, 3 }
// Create a Set of user objects
const users = new Set()

// Define user objects
const user1 = { id: 1, name: 'Rajnish' }
const user2 = { id: 2, name: 'Kumar' }
const user3 = { id: 3, name: 'Rahul' }

// Add users to the Set
users.add(user1)
users.add(user2)
users.add(user3)

// Check the size of the Set
console.log('Number of users:', users.size) // Output: Number of users: 3

// Try to add a duplicate user
users.add(user1)

// Check the size of the Set
console.log('Number of users:', users.size) // Output: Number of users: 3

// Iterate over the Set
users.forEach((user) => console.log(user.name))

// Output:
// Rajnish
// Kumar
// Rahul

Explanation:

  • We create a Set called users to store user objects.
  • We define three user objects (user1, user2, user3) with unique properties like id and name.
  • We add these user objects to the users Set using the add method. Sets ensure uniqueness, so duplicates will not be added.
  • We attempt to add user1 again to the Set, which won't be added as it's a duplicate.
  • We check the size of the Set using the size property, which returns the number of unique users.
  • We iterate over the Set using forEach to log each user's name.

Set with nested arrays of objects:

// Define an array of objects representing courses
const courses = [
  {
    id: 1,
    name: 'Mathematics',
    students: [
      { id: 101, name: 'Rajnish' },
      { id: 102, name: 'Kumar' },
    ],
  },
  {
    id: 2,
    name: 'Physics',
    students: [
      { id: 102, name: 'Kumar' },
      { id: 103, name: 'Rahul' },
    ],
  },
  {
    id: 3,
    name: 'Chemistry',
    students: [
      { id: 101, name: 'Rajnish' },
      { id: 103, name: 'Rahul' },
    ],
  },
]

// Initialize a Set to store unique student objects
const uniqueStudents = new Set()

// Iterate over courses to add students to the Set
courses.forEach((course) => {
  course.students.forEach((student) => {
    uniqueStudents.add(student)
  })
})

// Convert the Set back to an array for easier manipulation or display
const uniqueStudentsArray = Array.from(uniqueStudents)

// Log the unique students
console.log('Unique students:', uniqueStudentsArray)

// Output:

// Unique students: [
//   { id: 101, name: 'Rajnish' },
//   { id: 102, name: 'Kumar' },
//   { id: 103, name: 'Rahul' }
// ]

Explanation:

  • We have an array courses containing objects representing different courses, each with an id, name, and an array of students.
  • We initialize a Set called uniqueStudents to store unique student objects.
  • We iterate over each course in the courses array using forEach.
  • Within each course, we iterate over the students array and add each student object to the uniqueStudents Set.
  • Since Sets automatically handle uniqueness, duplicate student objects won't be added.
  • Finally, we convert the Set back to an array using Array.from to make it easier to manipulate or display.
  • We log the unique students array to the console.

Using new Set(courses) directly won't give you the desired result:

Using new Set(courses) directly won't give you the desired result because Set in JavaScript works with unique values, not objects. When you pass an array of objects to Set, it compares object references, not object properties. Since each object in your courses array is distinct, they won't be treated as duplicates even if they have similar properties.

Map Example:

const person = new Map()
person.set('name', 'Rajnish')
person.set('age', 30)
console.log(person.get('name')) // Output: Rajnish
console.log(person.get('age')) // Output: 30

To keep track of courses offered, their timings, and the rooms where they'll be conducted. Here's how you might use a Map to represent this information:

// Define a Map to store course schedules
const courseSchedule = new Map()

// Add course schedules to the Map
courseSchedule.set('Math101', {
  courseName: 'Mathematics',
  timings: 'Mon 10:00 AM - 12:00 PM',
  room: 'Room 101',
})
courseSchedule.set('Phys102', {
  courseName: 'Physics',
  timings: 'Tue 1:00 PM - 3:00 PM',
  room: 'Room 201',
})
courseSchedule.set('Chem103', {
  courseName: 'Chemistry',
  timings: 'Wed 9:00 AM - 11:00 AM',
  room: 'Room 301',
})

// Get information about a specific course
const courseID = 'Phys102'
const courseInfo = courseSchedule.get(courseID)

if (courseInfo) {
  console.log(`Course ${courseID}: ${courseInfo.courseName}`)
  console.log(`Timings: ${courseInfo.timings}`)
  console.log(`Room: ${courseInfo.room}`)
} else {
  console.log(`Course ${courseID} not found.`)
}

// Output:
// Course Phys102: Physics
// Timings: Tue 1:00 PM - 3:00 PM
// Room: Room 201

Explanation:

  • We're using a Map called courseSchedule to store course IDs as keys and course schedule objects as values.
  • Each schedule object contains information about the course name, timings, and room.
  • Map allows you to easily retrieve course schedules using their unique IDs (courseID). If a course ID is provided, the application fetches the corresponding course information from the Map and displays it. If the course ID doesn't exist in the Map, it notifies the user that the course wasn't found.