JS Destructuring
Make this exercise in Visual Studio Code and node.js.
These exercises practice the destructuring in JavaScript, which will be valuable when you start learning React.
Exercise:
Given the array:
const fruits = ['apple', 'banana', 'cherry'];
Use array destructuring to assign the values to variables firstFruit
, secondFruit
, and thirdFruit
. Print each variable to check the result.
Expected Output:
apple
banana
cherry
Exercise:
Given the array:
const colors = ['red', 'green', 'blue', 'yellow'];
Use destructuring to assign the first and third colors to firstColor
and thirdColor
, skipping the second color.
Expected Output:
red
blue
Exercise:
Given an array that might be missing values:
const numbers = [10, 20];
Use destructuring to assign num1
, num2
, and num3
, where num3
should default to 30 if it’s not in the array. Print each variable to check the result.
Expected Output:
num1: 10
num2: 20
num3: 30
Exercise:
Given the object:
const person = { name: 'Alice', age: 25, city: 'Wonderland' };
Use object destructuring to assign the name
, age
, and city
properties to separate variables. Print each variable to check the result.
Expected Output:
Alice
25
Wonderland
Exercise:
Given the object:
const book = { title: '1984', author: 'George Orwell', year: 1949 };
Use destructuring to assign title
to bookTitle
, author
to bookAuthor
, and year
to publicationYear
. Print each variable.
Expected Output:
bookTitle: 1984
bookAuthor: George Orwell
publicationYear: 1949
Exercise:
Given the object:
const student = {
name: 'Bob',
grade: 10,
subjects: {
math: 'A',
science: 'B'
}
};
Use nested destructuring to get name
, grade
, and the math
grade. Print each variable.
Expected Output:
Bob
10
A
Exercise:
Define a function displayPerson
that takes an object as a parameter with properties name
, age
, and city
. Use destructuring in the function’s parameter to access these properties directly. Call the function with:
displayPerson({ name: 'Charlie', age: 30, city: 'Paris' });
Expected Output:
Name: Charlie, Age: 30, City: Paris
Exercise:
Given two variables:
let a = 5;
let b = 10;
Use array destructuring to swap the values of a
and b
. Print the variables to check the result.
Expected Output:
a: 10
b: 5