Can you give an example for destruc...
Can you give an example for destruc...
Certainly! Destructuring is a powerful feature in ES6 (ECMAScript 2015) that allows you to unpack values from arrays or properties from objects into distinct variables. Here are examples for both array and object destructuring:
Array destructuring allows you to assign elements of an array to separate variables. Here's a simple example:
const numbers = [1, 2, 3, 4, 5];
const [first, second, , fourth] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(fourth); // Output: 4
In this example, first
, second
, and fourth
are variables that are assigned the first, second, and fourth values of the numbers
array respectively. Notice the use of an extra comma to skip the third element of the array.
Object destructuring allows you to extract multiple properties from an object and bind them to variables. Here's an example:
const person = {
name: 'John Doe',
age: 30,
location: 'New York'
};
const { name, age, location } = person;
console.log(name); // Output: John Doe
console.log(age); // Output: 30
console.log(location); // Output: New York
In this example, the name
, age
, and location
variables are created and assigned the corresponding properties from the person
object. This makes the code cleaner and easier to read, especially when dealing with multiple properties.
You can also destructure nested objects. Here's a more complex example:
const employee = {
id: 101,
name: 'Jane Doe',
position: {
title: ...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào