0% found this document useful (0 votes)
13 views8 pages

Default Parameters and Enhanced Object Literals

The document explains the use of default parameters in JavaScript functions to prevent errors when arguments are omitted, and demonstrates enhanced object literals for cleaner object creation. It covers shorthand syntax for properties and methods, computed property names, and provides exercises on creating modules and using spread/rest operators. Overall, it aims to improve code robustness and readability in ES6.

Uploaded by

Mohana D
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views8 pages

Default Parameters and Enhanced Object Literals

The document explains the use of default parameters in JavaScript functions to prevent errors when arguments are omitted, and demonstrates enhanced object literals for cleaner object creation. It covers shorthand syntax for properties and methods, computed property names, and provides exercises on creating modules and using spread/rest operators. Overall, it aims to improve code robustness and readability in ES6.

Uploaded by

Mohana D
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Default Parameters and Enhanced Object Literals

Default Parameters
Objective: Learn how to set default values for function parameters to make
functions more robust and avoid errors.
a. Setting Default Values for Function Arguments
In ES6, you can provide default values for function parameters. If no value is
passed when calling the function, the default value is used.
Example:
javascript
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}

greet("Alice"); // Output: Hello, Alice!


greet(); // Output: Hello, Guest!
● Explanation:
o If greet is called without any argument, name will take the default
value of "Guest".
o This prevents the function from throwing an error or printing
undefined.

b. Avoiding Undefined Errors in Function Calls


When default parameters are not used, omitting an argument can result in
undefined.
Without Default Parameters:
javascript
function multiply(a, b) {
return a * b; // Will return NaN if b is undefined
}

console.log(multiply(5)); // Output: NaN


With Default Parameters:
javascript
function multiply(a, b = 1) {
return a * b; // b defaults to 1 if not provided
}

console.log(multiply(5)); // Output: 5
● Explanation:
o Default parameters ensure that functions behave predictably, even
when arguments are missing.

c. Demo: Create a Function with Optional Parameters


javascript

function calculateTotal(price, taxRate = 0.05) {


return price + price * taxRate;
}

console.log(calculateTotal(100)); // Output: 105 (taxRate defaults to 0.05)


console.log(calculateTotal(100, 0.1)); // Output: 110 (taxRate is overridden to
0.1)
● Explanation:
o The taxRate parameter has a default value of 0.05. If a custom
taxRate is provided, it will override the default.
Enhanced Object Literals
Objective: Learn to simplify object creation and improve readability with
enhanced object literal syntax.

a. Shorthand for Object Properties and Methods


Shorthand for Properties: Before ES6:
javascript
const name = "Alice";
const age = 25;

const user = {
name: name,
age: age,
};
console.log(user); // Output: { name: 'Alice', age: 25 }
With ES6:
javascript
const name = "Alice";
const age = 25;

const user = { name, age };


console.log(user); // Output: { name: 'Alice', age: 25 }
● Explanation:
o If the property name and variable name are the same, you can omit
the key: value pair and write just the variable name.
Shorthand for Methods: Before ES6:
javascript
const user = {
sayHello: function () {
console.log("Hello!");
},
};
user.sayHello(); // Output: Hello!
With ES6:
javascript
const user = {
sayHello() {
console.log("Hello!");
},
};
user.sayHello(); // Output: Hello!
● Explanation:
o Methods can be defined without the function keyword for
simplicity.

b. Computed Property Names


Computed property names allow you to use expressions as keys in an object.
Example:
javascript
const key = "age";
const user = {
name: "Alice",
[key]: 25, // `key` is evaluated and becomes 'age'
};

console.log(user); // Output: { name: 'Alice', age: 25 }


● Explanation:
o The [key] syntax dynamically calculates the property name based
on the value of key.

Demo: Simplify Object Creation with Enhanced Object Literals


Creating a User Object:
javascript
const name = "Alice";
const age = 25;

const user = {
name,
age,
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age}
years old.`);
},
};

console.log(user);
// Output: { name: 'Alice', age: 25, greet: [Function: greet] }

user.greet(); // Output: Hello, my name is Alice and I am 25 years old.


● Explanation:
o Shorthand syntax makes the code cleaner.
o greet() is defined using the enhanced method syntax.
o Computed property names can also be added dynamically if
needed.
Exercise 1: Creating and Using a Simple Module
a. Write a Simple Module with Two Functions, add and subtract. Export
Them from One File and Import Them into Another.

Step-by-Step Guidance for Freshers:


1. Set Up Two Files:
o math.js: Contains the module with the add and subtract functions.
o main.js: Imports and uses the module.
2. In math.js:
o Write and export the functions.
javascript
// math.js
export function add(a, b) {
return a + b;
}

export function subtract(a, b) {


return a - b;
}
Explanation:
o export makes the functions available to other files.
o These functions perform basic arithmetic operations.
3. In main.js:
o Import and use the exported functions.
javascript
// main.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
Explanation:
o import { add, subtract } pulls specific functions from the math.js
module.
o The './math.js' path indicates the location of the module.
4. Run the Code:
o Use a browser with an ES6 module-supporting environment or a
Node.js setup.
o Include type="module" in an HTML <script> tag when running in
a browser.

Exercise 2: Working with Spread and Rest Operators (10 minutes)


a. Create an Array Using the Spread Operator to Combine Two Arrays
1. Combine Two Arrays:
javascript
const fruits = ['apple', 'banana'];
const vegetables = ['carrot', 'spinach'];
const food = [...fruits, ...vegetables];
console.log(food);
// Output: ['apple', 'banana', 'carrot', 'spinach']
Explanation:
o The ... (spread operator) "spreads" the elements of fruits and
vegetables into a new array.
o This creates a single array containing items from both.
2. Practical Use Case:
o Imagine you have separate lists of items (e.g., cart items). You can
merge them using the spread operator.
b. Use the Rest Operator in a Function to Accept Multiple Arguments and
Log the Results
1. Write a Function Using the Rest Operator:
javascript
function logNumbers(...numbers) {
console.log(numbers);
}

logNumbers(1, 2, 3, 4, 5);
// Output: [1, 2, 3, 4, 5]
Explanation:
o The ...numbers (rest operator) collects all arguments passed to the
function into an array.
o You can process an unknown number of inputs dynamically.
2. Calculate the Sum of Numbers Using Rest Operator:
javascript
function calculateSum(...numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}

console.log(calculateSum(1, 2, 3));
// Output: 6
Explanation:
o reduce() processes the array created by the rest operator and
calculates the sum.
o The rest operator simplifies handling multiple arguments without
explicitly defining them.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy