Next Topic ⮕
Iterating over Objects in JavaScriptYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.
Next Topic ⮕
Iterating over Objects in JavaScriptDestructuring assignment in JavaScript is a convenient way to extract values from arrays or properties from objects into distinct variables. It simplifies your code and makes it more readable, especially when dealing with complex data structures.
Let’s start by understanding how we can destructure values from arrays.
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor, thirdColor] = colors;
console.log(firstColor);
console.log(secondColor);
console.log(thirdColor);
red green blue
Suppose you receive an array from a function. Instead of writing:
const result = [1, 2];
const x = result[0];
const y = result[1];
You can write:
const [x, y] = result;
Cleaner, right?
You can skip elements in an array while destructuring:
const numbers = [10, 20, 30];
const [ , , third] = numbers;
console.log(third);
30
Now let’s explore object destructuring. It allows you to pull out properties from an object into variables.
const person = {
name: 'Alice',
age: 25,
country: 'India'
};
const { name, age } = person;
console.log(name);
console.log(age);
Alice 25
You can also assign a property to a variable with a different name:
const user = {
id: 101,
username: 'john_doe'
};
const { username: userName } = user;
console.log(userName);
john_doe
What if the property does not exist? You can set a default value during destructuring:
const profile = { name: 'Jane' };
const { name, city = 'Unknown' } = profile;
console.log(city);
Unknown
JavaScript also supports nested destructuring:
const employee = {
id: 501,
details: {
fullName: 'David Smith',
department: 'Sales'
}
};
const { details: { fullName } } = employee;
console.log(fullName);
David Smith
You can destructure directly in function arguments for cleaner code:
function greet({ name, age }) {
console.log(`Hello, ${name}. You are ${age} years old.`);
}
greet({ name: 'Emily', age: 30 });
Hello, Emily. You are 30 years old.
Question: What will be the output of the following?
const fruits = ['apple'];
const [firstFruit, secondFruit = 'banana'] = fruits;
console.log(secondFruit);
Answer: banana
. Since the second element is undefined, the default is used.
Next Topic ⮕
Iterating over Objects in JavaScriptYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.