Câu hỏi phỏng vấn Javascript
Câu hỏi

Can you give an example for destruc...

Câu trả lời

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

Array destructuring allows you to assign elements of an array to separate variables. Here's a simple example:

javascript Copy
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

Object destructuring allows you to extract multiple properties from an object and bind them to variables. Here's an example:

javascript Copy
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.

Advanced Example with Nested Objects

You can also destructure nested objects. Here's a more complex example:

javascript Copy
const employee = {
    id: 101,
    name: 'Jane Doe',
    position: {
        title: ...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

Describe Closure concept in JavaScript as best as you could

middle

What is Coercion in JavaScript?

senior

How can you share code between files?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào