Destructuring in JavaScript | Lecture 5

 

Destructuring in JavaScript is a syntax for unpacking values from arrays or properties from objects into distinct variables. This feature simplifies extracting data, making your code cleaner and more readable. Here are examples of destructuring for both arrays and objects:


1. Destructuring Arrays

const fruits = ['apple', 'banana', 'cherry'];

 

// Basic Destructuring

const [first, second] = fruits;

console.log(first); // "apple"

console.log(second); // "banana"

 

// Skipping Elements

const [, , third] = fruits;

console.log(third); // "cherry"

 

// Default Values

const [a, b, c = 'default fruit'] = ['mango', 'pear'];

console.log(c); // "default fruit"

 

// Rest Pattern

const [d, ...rest] = fruits;

console.log(rest); // ["banana", "cherry"]


2. Destructuring Objects

const user = {

  name: 'John',

  age: 30,

  country: 'USA',

};

 

// Basic Destructuring

const { name, age } = user;

console.log(name); // "John"

console.log(age); // 30

 

// Renaming Variables

const { name: userName, country: userCountry } = user;

console.log(userName); // "John"

console.log(userCountry); // "USA"

 

// Default Values

const { city = 'Unknown' } = user;

console.log(city); // "Unknown"

 

// Rest Pattern

const { name: n, ...rest } = user;

console.log(rest); // { age: 30, country: 'USA' }


3. Nested Destructuring

Array Example:

const numbers = [1, [2, 3], 4];

const [one, [two, three]] = numbers;

console.log(two); // 2

console.log(three); // 3

Object Example:

const employee = {

  id: 1,

  details: {

    name: 'Alice',

    department: 'Engineering',

  },

};

 

const {

  details: { name, department },

} = employee;

console.log(name); // "Alice"

console.log(department); // "Engineering"


4. Destructuring in Functions

Parameters:

function greet({ name, age }) {

  console.log(`Hello, ${name}! You are ${age} years old.`);

}

 

const person = { name: 'Sam', age: 25 };

greet(person); // "Hello, Sam! You are 25 years old."

Returning Multiple Values:

function getCoordinates() {

  return { x: 10, y: 20 };

}

 

const { x, y } = getCoordinates();

console.log(x, y); // 10 20


Destructuring is a powerful tool for simplifying code and improving readability, especially when dealing with complex data structures.

 

Comments

Popular posts from this blog

Classes and Objects in Javascript | Lecture 10

ECMA Script 6 Introduction of topics | Lecture 1