Destructuring In JavaScript

Destructuring In JavaScript

Destructuring is a feature in JavaScript that allows you to extract values from arrays or properties from objects and assign them to variables in a more concise way. This can make your code cleaner and more readable. Destructuring is commonly used in assignments and function parameter definitions.

Array Destructuring:

Basic syntax:

let [variable1, variable2, ...rest] = array;        

Example:

let numbers = [1, 2, 3, 4, 5];
let [first, second, third] = numbers;

console.log(first);  // Output: 1
console.log(second); // Output: 2
console.log(third);  // Output: 3        

Skipping elements:

let [first, , third] = numbers;

console.log(first);  // Output: 1
console.log(third);  // Output: 3        

Rest parameter:

let [first, ...rest] = numbers;

console.log(first); // Output: 1
console.log(rest);  // Output: [2, 3, 4, 5]        
Object Destructuring:

Basic syntax:

let { property1, property2 } = object;        

Example:

let person = { name: 'John', age: 30, city: 'New York' };
let { name, age } = person;

console.log(name); // Output: John
console.log(age);  // Output: 30        

Renaming variables:

let { name: personName, age: personAge } = person;

console.log(personName); // Output: John
console.log(personAge);  // Output: 30        

Default values:

let { name, age, job = 'Developer' } = person;

console.log(name); // Output: John
console.log(age);  // Output: 30
console.log(job);  // Output: Developer        
Nested Destructuring:

Nested Array and Object Destructuring:

let nestedData = [1, 2, [3, 4], { key: 'value' }];
let [first, second, [third, fourth], { key }] = nestedData;

console.log(first, second, third, fourth, key);
// Output: 1 2 3 4 value        
Function Parameter Destucturing:

Example:

function printPersonDetails({ name, age }) {
  console.log(`Name: ${name}, Age: ${age}`);
}

printPersonDetails(person); // Output: Name: John, Age: 30        

Imagine you had a data object that looked like this:
const data = {
  color: 'blue',
  cost: 40,
  name: 'ribbon'
}        

Without destructuring, we could access the values like this:

// ..
console.log(`The cost of the ${data.color} ${data.name} is ${data.cost}`)
// => 'The cost of blue ribbon is 40'        

With destructuring you can pull multiple values off an object:

// ..
const { color, cost, name } = data
console.log(`The cost of the ${color} ${name} is ${cost}`)
// => 'The cost of the blue ribbon is 40'        

What about nested objects? If you want to access the items from just one key, you can put the key on the right side of the equal sign:

const data = {
  user: {
    name: 'Dave',
    email: '[email protected]'
  }
}

const { name, email } = data.user
console.log(`The email of ${name} is ${email}`)
// => 'The email of Dave is [email protected]'        

What if you want values from multiple levels? No Problem:

const data = {
  user: {
    name: 'Dave',
    email: '[email protected]'
    activity: {
      status: 'inactive',
      lastLoggedIn: 'yesterday'
    }
  }
}

const { name, activity: { status, lastLoggedIn }} = data.user
console.log(`${name} logged in ${lastLoggedIn} and is currently ${status}`)
// => 'Dave logged in yesterday and is currently inactive'        

These examples provide a basic overview of array and object destructuring in JavaScript. Destructuring can be a powerful tool for simplifying code and making it more expressive.

要查看或添加评论,请登录

Sumit Mishra的更多文章

  • CSS Specificity

    CSS Specificity

    CSS specificity is a set of rules used to determine which styles are applied to an element when multiple conflicting…

  • Install & Run Typescript

    Install & Run Typescript

    To compile TypeScript code into JavaScript, you need to have the TypeScript compiler () installed. You can install it…

  • Php 8 New Concepts

    Php 8 New Concepts

    PHP 8 introduced several new features and improvements. Here are some of the key concepts with examples: Named…

  • useRef Hook In React Js

    useRef Hook In React Js

    In React, the hook is used to create a mutable object called a ref. This ref can be attached to a React element and can…

  • Children In React Js

    Children In React Js

    In React.js, handling children is a fundamental aspect of building components.

  • Abstract Data Type In Detail

    Abstract Data Type In Detail

    An Abstract Data Type (ADT) is a high-level description of a set of operations that can be performed on a particular…

  • API resources In Laravel

    API resources In Laravel

    In Laravel, API resources provide a convenient way to transform and format your Eloquent models and collections into a…

  • Flux Pattern In React Js With Example

    Flux Pattern In React Js With Example

    Install Dependencies: You'll need to install package. You can install it using npm or yarn: or Implement Flux…

  • Rules of Hooks In React Js

    Rules of Hooks In React Js

    In React, hooks are functions that allow you to use state and other React features in functional components. The most…

  • What is Cron Jobs. How to Implement Cron Jobs in Php

    What is Cron Jobs. How to Implement Cron Jobs in Php

    Cron jobs in PHP are scheduled tasks that run automatically at predefined intervals on a Unix-based system. These tasks…

社区洞察

其他会员也浏览了