Assignments Of day 14: JavaScript ES6 Features
Assignment 1: Arrow Function
Problem: Write an arrow function multiply that takes two numbers as arguments and returns their product.
Step-by-Step Solution:
1. Define an arrow function named multiply that takes two parameters: num1 and num2.
2. The function should return the product of num1 and num2.
javascript
Copy code
const multiply = (num1, num2) => num1 * num2; // Arrow function that multiplies two numbers
3. Now, call the function with two numbers and log the result:
javascript
Copy code
console.log(multiply(5, 10)); // Output: 50
Explanation:
- The arrow function syntax (num1, num2) => num1 * num2 is a concise way to define a function that multiplies two numbers.
- The console.log(multiply(5, 10)) logs the result of the multiplication to the console.
Assignment 2: Template Literals
Problem: Create a string using template literals to display the following sentence: "Hello, my name is John and I am 30 years old."
Step-by-Step Solution:
1. Define variables for name and age.
2. Use template literals to insert these values into a string.
javascript
Copy code
let name = "John";
let age = 30;
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);
Explanation:
- We use backticks () for template literals, and ${}` is used to embed variables or expressions within the string.
- The output will be: "Hello, my name is John and I am 30 years old.".
Assignment 3: Destructuring Arrays
Problem: Given the following array const numbers = [1, 2, 3, 4], use array destructuring to assign the first two values to first and second variables.
Step-by-Step Solution:
1. Use destructuring to assign the first two values of the numbers array to first and second.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const [first, second] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
Explanation:
- Array destructuring allows you to directly unpack values from an array into individual variables.
- const [first, second] = numbers; extracts the first and second elements of the array into the variables first and second.
Assignment 4: Destructuring Objects
Problem: Given the object const person = { name: 'Alice', age: 25, country: 'USA' }, use object destructuring to extract name and age into separate variables.
Step-by-Step Solution:
1. Use object destructuring to extract name and age from the person object.
javascript
Copy code
const person = { name: 'Alice', age: 25, country: 'USA' };
const { name, age } = person;
console.log(name); // Output: Alice
console.log(age); // Output: 25
Explanation:
- In object destructuring, we extract the properties name and age directly from the object and assign them to variables of the same name.
- The output will display the values "Alice" and 25 for name and age, respectively.
Assignment 5: let and const with Block Scope
Problem:
1. Declare a variable x using let inside a block. Modify the value of x inside the block.
2. Declare a constant PI using const and attempt to modify its value to see the result.
Step-by-Step Solution:
1. First, declare x using let inside a block and modify its value.
javascript
Copy code
{
let x = 10; // Declaring variable with let inside a block
x = 20; // Reassigning the value of x
console.log(x); // Output: 20
}
2. Next, declare a constant PI and attempt to reassign its value.
javascript
Copy code
const PI = 3.14;
PI = 3.1415; // Error: Assignment to constant variable.
Explanation:
- let allows you to modify the value of x inside the block, and the scope of x is limited to that block.
- const declares a constant whose value cannot be reassigned. Attempting to change the value of PI will result in an error because const variables are immutable.
Assignment 6: Destructuring with Renaming Variables
Problem: Given the object const user = { username: 'john_doe', email: 'john@example.com' }, use destructuring to extract username and email properties, but assign them to new variable names: userName and userEmail.
Step-by-Step Solution:
1. Use object destructuring and rename the variables.
javascript
Copy code
const user = { username: 'john_doe', email: 'john@example.com' };
const { username: userName, email: userEmail } = user;
console.log(userName); // Output: john_doe
console.log(userEmail); // Output: john@example.com
Explanation:
- When destructuring an object, you can rename the extracted values by using the newName: originalName syntax.
- In this example, username is renamed to userName, and email is renamed to userEmail.
Assignment 7: Using let and const Together
Problem: Declare a const variable for a country and a let variable for the capital. Change the value of the capital and print both.
Step-by-Step Solution:
1. Declare the const and let variables.
2. Modify the value of the capital and log both values.
javascript
Copy code
const country = 'Japan';
let capital = 'Tokyo';
capital = 'Kyoto'; // Changing the value of capital
console.log(country); // Output: Japan
console.log(capital); // Output: Kyoto
Explanation:
- const is used for the country because its value shouldn't change.
- let is used for the capital because its value can be reassigned.
Assignment 8: Combine Template Literals and Destructuring
Problem: Given the object const person = { name: 'Tom', job: 'Developer', age: 28 }, use destructuring to extract name, job, and age, and then use template literals to create a sentence: "Tom is a 28-year-old Developer."
Step-by-Step Solution:
1. Destructure the person object.
2. Use template literals to create the sentence.
javascript
Copy code
const person = { name: 'Tom', job: 'Developer', age: 28 };
const { name, job, age } = person;
let message = `${name} is a ${age}-year-old ${job}.`;
console.log(message); // Output: Tom is a 28-year-old Developer.
Explanation:
- We first destructure the object to extract name, job, and age.
- Then, we use template literals to insert these values into a sentence.
Assignment 9: Function with Arrow Functions and Template Literals
Problem: Write an arrow function greet that takes a name as a parameter and returns a greeting string using template literals.
Step-by-Step Solution:
1. Write the arrow function greet that accepts name as an argument.
2. Use template literals to return a greeting.
javascript
Copy code
const greet = name => `Hello, ${name}! Welcome to the ES6 world.`;
console.log(greet("Alice")); // Output: Hello, Alice! Welcome to the ES6 world.
Explanation:
- The arrow function greet uses a template literal to insert the name into the greeting message.
- The result is a string that includes the name passed to the function.
These assignments help practice the core ES6 concepts with real-world examples and step-by-step solutions.
4o mini
You said:
give more
ChatGPT said:
ChatGPT
Here are additional assignments based on JavaScript ES6 Features for practice:
Assignment 10: Arrow Function with Default Parameters
Problem: Write an arrow function calculatePrice that takes two parameters price and taxRate. If the taxRate is not provided, use a default value of 0.1. The function should return the total price after applying the tax.
Step-by-Step Solution:
1. Define an arrow function calculatePrice that accepts price and taxRate.
2. Set a default value of 0.1 for taxRate.
3. Return the total price, which is the sum of price and the calculated tax.
javascript
Copy code
const calculatePrice = (price, taxRate = 0.1) => price + price * taxRate;
console.log(calculatePrice(100)); // Output: 110
console.log(calculatePrice(100, 0.2)); // Output: 120
Explanation:
- The taxRate = 0.1 ensures that if the second parameter is omitted, the default value 0.1 will be used.
- The function calculates the total price by applying the tax rate to the price.
Assignment 11: Template Literals with Expressions
Problem: Create a template literal that calculates the area of a rectangle. The rectangle's length is 10 and width is 5. The template literal should output the message: "The area of the rectangle is 50 square units."
Step-by-Step Solution:
1. Define the length and width variables.
2. Use a template literal with an expression to calculate the area.
javascript
Copy code
const length = 10;
const width = 5;
const areaMessage = `The area of the rectangle is ${length * width} square units.`;
console.log(areaMessage); // Output: The area of the rectangle is 50 square units.
Explanation:
- Template literals allow embedding expressions within ${}. Here, length * width calculates the area of the rectangle directly inside the template literal.
Assignment 12: Object Destructuring with Nested Objects
Problem: Given the following object:
javascript
Copy code
const user = {
id: 1,
profile: {
name: 'John Doe',
age: 30
}
};
Use destructuring to extract name and age from the profile object inside user.
Step-by-Step Solution:
1. Destructure the profile object from the user object.
2. Extract name and age from the profile.
javascript
Copy code
const user = {
id: 1,
profile: {
name: 'John Doe',
age: 30
}
};
const { profile: { name, age } } = user;
console.log(name); // Output: John Doe
console.log(age); // Output: 30
Explanation:
- We used nested destructuring to directly access the name and age properties from the profile object inside user.
Assignment 13: Using let and const in Loops
Problem: You have an array of numbers: [1, 2, 3, 4, 5]. Using a for loop, iterate over the array and print each number. Use let for the loop variable.
Step-by-Step Solution:
1. Define the array.
2. Use a for loop with let to iterate through each element.
javascript
Copy code
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
Explanation:
- Using let for the loop variable i ensures that i has a block scope and will be re-assigned on each iteration.
Assignment 14: let and const with Conditional Blocks
Problem:
1. Use let inside an if block to change a variable's value.
2. Declare a constant with const and attempt to change its value.
Step-by-Step Solution:
1. Declare a variable x using let inside the block and change its value.
2. Attempt to reassign the value of a constant.
javascript
Copy code
{
let x = 10;
x = 20; // Reassigning the value of x
console.log(x); // Output: 20
}
{
const y = 30;
y = 40; // Error: Assignment to constant variable.
}
Explanation:
- let allows reassignment within the block, while const does not allow reassignment after initialization.
Assignment 15: Destructuring with Default Values
Problem: Given the object const person = { name: 'Alice' }, use destructuring to extract name and age. If age is not present in the object, assign a default value of 25.
Step-by-Step Solution:
1. Use object destructuring with default value for age.
javascript
Copy code
const person = { name: 'Alice' };
const { name, age = 25 } = person;
console.log(name); // Output: Alice
console.log(age); // Output: 25
Explanation:
- The destructuring syntax allows you to provide a default value (age = 25) if the property is not found in the object.
Assignment 16: Arrow Function with Multiple Statements
Problem: Write an arrow function getRectangleDetails that accepts the length and width of a rectangle, calculates the area and perimeter, and returns them as an object. Use multiple statements within the arrow function.
Step-by-Step Solution:
1. Define the getRectangleDetails function with multiple statements.
2. Return the area and perimeter as an object.
javascript
Copy code
const getRectangleDetails = (length, width) => {
const area = length * width;
const perimeter = 2 * (length + width);
return { area, perimeter };
};
console.log(getRectangleDetails(5, 10)); // Output: { area: 50, perimeter: 30 }
Explanation:
- The arrow function uses multiple statements by enclosing them in curly braces {}. The object returned contains both the area and perimeter of the rectangle.
Assignment 17: Combining Arrow Functions and Template Literals
Problem: Write an arrow function createGreeting that takes firstName and lastName as parameters, and returns a greeting message using template literals: "Hello, FirstName LastName!".
Step-by-Step Solution:
1. Define the arrow function createGreeting.
2. Use template literals to generate the greeting message.
javascript
Copy code
const createGreeting = (firstName, lastName) => `Hello, ${firstName} ${lastName}!`;
console.log(createGreeting("John", "Doe")); // Output: Hello, John Doe!
Explanation:
- The arrow function combines the use of template literals to create a string greeting by embedding the firstName and lastName values.
Assignment 18: Destructuring Arrays with Skipping Elements
Problem: Given the array const colors = ['red', 'green', 'blue', 'yellow', 'purple'], use array destructuring to extract red and blue, skipping over the elements in between.
Step-by-Step Solution:
1. Use array destructuring with a comma to skip elements.
javascript
Copy code
const colors = ['red', 'green', 'blue', 'yellow', 'purple'];
const [firstColor, , thirdColor] = colors;
console.log(firstColor); // Output: red
console.log(thirdColor); // Output: blue
Explanation:
- The commas in array destructuring ([firstColor, , thirdColor]) are used to skip over the elements you don't want to extract.
Assignment 19: Using const for Immutable Objects
Problem: Create an object book with properties title and author. Use const to declare the object, but change the values of the properties.
Step-by-Step Solution:
1. Declare an object using const.
2. Modify the values of its properties.
javascript
Copy code
const book = { title: 'JavaScript Basics', author: 'John Doe' };
book.title = 'Advanced JavaScript'; // Modifying a property
book.author = 'Jane Smith'; // Modifying a property
console.log(book); // Output: { title: 'Advanced JavaScript', author: 'Jane Smith' }
Explanation:
- const ensures that the reference to the object cannot be changed, but its properties can still be modified.
Assignment 20: Arrow Function with Implicit Return
Problem: Write an arrow function square that takes a number as input and returns its square. Use the implicit return feature of the arrow function.
Step-by-Step Solution:
1. Define the square function using implicit return.
javascript
Copy code
const square = num => num * num;
console.log(square(5)); // Output: 25
Explanation:
- The arrow function square has an implicit return since the function body is a single expression.
Let me know if you'd like more assignments or if you'd like to dive deeper into any particular concept!
4o mini
You said:
give more variety to know this concept more well and deep
ChatGPT said:
ChatGPT
Here are additional and more varied assignments to help understand JavaScript ES6 Features in greater depth. These assignments will cover different aspects, such as combining multiple features, more complex destructuring, and real-world application of ES6 concepts:
Assignment 21: Combining Arrow Functions, Template Literals, and Destructuring
Problem: Write an arrow function userInfo that takes an object with properties firstName, lastName, and age. The function should return a string that says: "FirstName LastName is age years old." Use arrow functions, destructuring, and template literals in your solution.
Step-by-Step Solution:
1. Use destructuring to extract firstName, lastName, and age from the object.
2. Use a template literal to format the string.
javascript
Copy code
const userInfo = ({ firstName, lastName, age }) => `${firstName} ${lastName} is ${age} years old.`;
const user = { firstName: 'John', lastName: 'Doe', age: 30 };
console.log(userInfo(user)); // Output: John Doe is 30 years old.
Explanation:
- Destructuring extracts properties from the object, and template literals are used to create a formatted message.
Assignment 22: Arrow Functions with Multiple Parameters and Return Object
Problem: Write an arrow function createPerson that takes two parameters name and age. The function should return an object with properties name and age as well as a method greet that returns a greeting message.
Step-by-Step Solution:
1. Define the createPerson arrow function that returns an object.
2. The object will have properties name and age, and a method greet.
javascript
Copy code
const createPerson = (name, age) => ({
name,
age,
greet: () => `Hello, my name is ${name} and I am ${age} years old.`
});
const person = createPerson('Alice', 25);
console.log(person.greet()); // Output: Hello, my name is Alice and I am 25 years old.
Explanation:
- The arrow function returns an object using shorthand property names (name and age), and the greet method is defined inside the returned object.
Assignment 23: Using Destructuring with Function Parameters
Problem: Write a function getFullName that takes an object with firstName and lastName properties, and returns the full name by combining both values.
Step-by-Step Solution:
1. Use destructuring in the function parameter to extract firstName and lastName.
2. Return the full name.
javascript
Copy code
const getFullName = ({ firstName, lastName }) => `${firstName} ${lastName}`;
const person = { firstName: 'John', lastName: 'Smith' };
console.log(getFullName(person)); // Output: John Smith
Explanation:
- The function accepts an object and destructures its properties directly in the function's parameter list.
Assignment 24: Template Literals with Expressions
Problem: Write a program that calculates the area and perimeter of a circle using template literals. The radius is 7.
Step-by-Step Solution:
1. Define the radius.
2. Use template literals to compute and display both area and perimeter.
javascript
Copy code
const radius = 7;
const area = Math.PI * radius * radius;
const perimeter = 2 * Math.PI * radius;
const result = `For a circle with radius ${radius}:
- Area: ${area.toFixed(2)}
- Perimeter: ${perimeter.toFixed(2)}`;
console.log(result);
Explanation:
- Template literals make it easier to embed expressions like Math.PI * radius * radius directly into a string.
Assignment 25: Destructuring with Arrays and Default Values
Problem: Given the array [1, 2, 3, 4], use array destructuring to assign first to the first element, second to the second, and a default value of 10 for the third element.
Step-by-Step Solution:
1. Use destructuring with default values to extract elements from the array.
javascript
Copy code
const arr = [1, 2, 3, 4];
const [first, second, third = 10] = arr;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(third); // Output: 3 (not 10, since the third element exists)
Explanation:
- The default value 10 is used for third in case the array has fewer elements.
Assignment 26: Using let and const in Loops
Problem: Write a program that loops over an array of strings: ['apple', 'banana', 'cherry']. Use let to store the current string in the loop and const for the array.
Step-by-Step Solution:
1. Define the array using const and loop through it using let.
javascript
Copy code
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
let fruit = fruits[i];
console.log(fruit); // Output: apple, banana, cherry
}
Explanation:
- const is used for the array since its reference does not change, and let is used to create a new variable fruit for each iteration.
Assignment 27: Arrow Function with No Parameters
Problem: Write an arrow function sayHello that takes no parameters and returns the string "Hello, World!".
Step-by-Step Solution:
1. Define an arrow function with no parameters.
javascript
Copy code
const sayHello = () => 'Hello, World!';
console.log(sayHello()); // Output: Hello, World!
Explanation:
- An arrow function with no parameters simply uses empty parentheses ().
Assignment 28: Destructuring Nested Arrays
Problem: Given the array const data = [1, [2, 3], 4], use array destructuring to extract the values 1, 2, and 4.
Step-by-Step Solution:
1. Use nested array destructuring to extract the values.
javascript
Copy code
const data = [1, [2, 3], 4];
const [first, [second], third] = data;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(third); // Output: 4
Explanation:
- The array is destructured in two levels: the first level extracts 1, and the second level extracts 2 from the nested array.
Assignment 29: Combining Multiple Destructurings
Problem: Given the object const student = { name: 'Emma', marks: { math: 90, science: 85 }, age: 20 }, destructure the object to extract name, mathMarks, and age.
Step-by-Step Solution:
1. Destructure the object and nested marks object.
javascript
Copy code
const student = { name: 'Emma', marks: { math: 90, science: 85 }, age: 20 };
const { name, marks: { math: mathMarks }, age } = student;
console.log(name); // Output: Emma
console.log(mathMarks); // Output: 90
console.log(age); // Output: 20
Explanation:
- Nested destructuring allows extracting math from the marks object and renaming it to mathMarks.
Assignment 30: Using Arrow Functions and Higher-Order Functions
Problem: Given an array of numbers [1, 2, 3, 4], use the map method to create a new array where each number is squared. Use an arrow function to do this.
Step-by-Step Solution:
1. Use the map method with an arrow function to square each element.
javascript
Copy code
const numbers = [1, 2, 3, 4];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16]
Explanation:
- map is a higher-order function that applies the arrow function to each element of the array, returning a new array of squared values.
These assignments cover a range of scenarios to deepen your understanding of ES6 features in JavaScript, from destructuring complex objects and arrays to working with modern syntax like arrow functions and template literals. Let me know if you'd like even more challenging problems!
4o mini
You said:
give more variety to know this concept more well and deep
ChatGPT said:
ChatGPT
Here are even more varied and in-depth assignments to help understand and apply JavaScript ES6 Features such as arrow functions, template literals, destructuring, and let/const:
Assignment 31: Refactoring a Regular Function to an Arrow Function
Problem: You have a regular function multiply that multiplies two numbers. Refactor it to use an arrow function. Also, ensure that the arrow function is concise.
Step-by-Step Solution:
1. Write the regular function.
2. Convert it into an arrow function.
javascript
Copy code
// Regular function
function multiply(a, b) {
return a * b;
}
// Arrow function (concise version)
const multiplyArrow = (a, b) => a * b;
console.log(multiplyArrow(2, 3)); // Output: 6
Explanation:
- The regular function is refactored to an arrow function. Since the function has a single return statement, it uses a concise syntax (no curly braces or return keyword).
Assignment 32: Creating an Object with Arrow Functions
Problem: Write an arrow function createPerson that takes two parameters firstName and lastName. The function should return an object with those parameters as well as a method introduce that returns a string saying: "Hi, I’m firstName lastName".
Step-by-Step Solution:
1. Use arrow function to return an object.
2. Inside the object, include a method that uses template literals.
javascript
Copy code
const createPerson = (firstName, lastName) => ({
firstName,
lastName,
introduce: () => `Hi, I'm ${firstName} ${lastName}.`
});
const person = createPerson('Alice', 'Johnson');
console.log(person.introduce()); // Output: Hi, I'm Alice Johnson.
Explanation:
- The arrow function returns an object, and within it, a method introduce uses a template literal to introduce the person.
Assignment 33: Destructuring with Default Values in Function Arguments
Problem: You are given a function createProfile that takes an object with name, age, and email. If age or email is missing from the object, use default values for them. Destructure the object in the function argument.
Step-by-Step Solution:
1. Use destructuring in the function argument with default values.
javascript
Copy code
const createProfile = ({ name, age = 25, email = 'Not Provided' }) => {
return `Name: ${name}, Age: ${age}, Email: ${email}`;
};
console.log(createProfile({ name: 'John' }));
// Output: Name: John, Age: 25, Email: Not Provided
console.log(createProfile({ name: 'Doe', age: 30, email: 'doe@example.com' }));
// Output: Name: Doe, Age: 30, Email: doe@example.com
Explanation:
- Destructuring is used in the function parameter to extract values. Default values for age and email are applied if not present.
Assignment 34: Destructuring Nested Objects with Renaming
Problem: Given an object const student = { name: 'Emma', contact: { email: 'emma@example.com', phone: '123-456-7890' }, age: 20 }, destructure the object and rename email to contactEmail and phone to contactPhone.
Step-by-Step Solution:
1. Use nested destructuring and rename properties.
javascript
Copy code
const student = {
name: 'Emma',
contact: { email: 'emma@example.com', phone: '123-456-7890' },
age: 20
};
const { name, contact: { email: contactEmail, phone: contactPhone }, age } = student;
console.log(contactEmail); // Output: emma@example.com
console.log(contactPhone); // Output: 123-456-7890
Explanation:
- Nested destructuring allows extracting values from the contact object and renaming them as contactEmail and contactPhone.
Assignment 35: Template Literals with Conditional Statements
Problem: Write a function getGrade that returns a grade message based on a score using template literals and conditional logic. For example, if the score is above 90, return "A", above 75 return "B", otherwise "C".
Step-by-Step Solution:
1. Use template literals inside the return statement along with a conditional check.
javascript
Copy code
const getGrade = (score) => {
const grade = score > 90 ? 'A' : score > 75 ? 'B' : 'C';
return `Your grade is: ${grade}`;
};
console.log(getGrade(85)); // Output: Your grade is: B
console.log(getGrade(95)); // Output: Your grade is: A
console.log(getGrade(60)); // Output: Your grade is: C
Explanation:
- Template literals are used to inject the result of the conditional logic directly into the string.
Assignment 36: Using let and const in Loops (Block Scope)
Problem: Write a loop that demonstrates the difference between let and const in terms of scope. Declare variables inside the loop using both let and const and observe the behavior.
Step-by-Step Solution:
1. Use let to define a loop variable and const for a constant inside the loop.
2. Test how let allows reassignment and const does not.
javascript
Copy code
for (let i = 0; i < 3; i++) {
let number = i;
const fixedValue = 10;
console.log(`Loop ${i}: number = ${number}, fixedValue = ${fixedValue}`);
}
// Trying to reassign const will give an error
// fixedValue = 20; // This will throw an error.
Explanation:
- let allows block scoping, meaning its value can change within each iteration of the loop.
- const creates a constant within the block scope, which cannot be reassigned.
Assignment 37: Default Parameters in Arrow Functions
Problem: Write an arrow function sum that takes two numbers and returns their sum. If a parameter is missing, use 0 as the default value.
Step-by-Step Solution:
1. Use default parameters in the arrow function.
javascript
Copy code
const sum = (a = 0, b = 0) => a + b;
console.log(sum(5, 3)); // Output: 8
console.log(sum(5)); // Output: 5 (default value for b is 0)
console.log(sum()); // Output: 0 (both a and b are 0)
Explanation:
- Default parameters ensure that the function works even if one or both arguments are missing.
Assignment 38: Arrow Functions and Higher-Order Functions
Problem: Write a program that uses map() and an arrow function to convert an array of temperatures from Celsius to Fahrenheit. Use the formula F = (C * 9/5) + 32.
Step-by-Step Solution:
1. Use map() with an arrow function to process each item in the array.
javascript
Copy code
const celsius = [0, 20, 30, 40];
const fahrenheit = celsius.map(temp => (temp * 9/5) + 32);
console.log(fahrenheit); // Output: [32, 68, 86, 104]
Explanation:
- map() is a higher-order function that transforms each element in the array using the arrow function.
Assignment 39: Using Template Literals with Multiline Strings
Problem: Write a function generateMessage that returns a multiline string using template literals. The message should contain a header, body, and footer.
Step-by-Step Solution:
1. Use backticks (`) to create multiline strings.
javascript
Copy code
const generateMessage = () => {
return `
=== Message ===
Hello, this is a multiline message.
We are learning ES6 features in JavaScript.
===================
`;
};
console.log(generateMessage());
Explanation:
- Template literals allow for multiline strings without the need for escape characters like \n.
Assignment 40: Destructuring Function Return Values
Problem: Write a function getCoordinates that returns an object containing x and y. Destructure the object in the calling code to extract the x and y values.
Step-by-Step Solution:
1. Return an object from the function and destructure it when calling.
javascript
Copy code
const getCoordinates = () => ({ x: 5, y: 10 });
const { x, y } = getCoordinates();
console.log(`x: ${x}, y: ${y}`); // Output: x: 5, y: 10
Explanation:
- The function returns an object, and the calling code uses destructuring to extract and use the x and y values.
