[JavaScript] Implementation Techniques for Setting Default Values for Function Arguments

目次

Overview

When designing functions, there are cases where certain arguments should be optional. In JavaScript (ES6 and later), it is possible to set “default values” within the argument definition. These values are automatically applied if the caller does not provide a value. This allows for the smart management of mandatory and optional parameters while preventing “undefined” errors.

Specifications (Input/Output)

  • Input:
    • Purchase amount (Mandatory)
    • Point multiplier (Optional; defaults to 1x if omitted)
  • Output: Console output of the calculated points.

Basic Usage

To set a default value, write parameterName = defaultValue in the function’s argument list. This default value is activated only when the argument is omitted or when undefined is explicitly passed.

Full Code (HTML / JavaScript)

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Default Parameters Demo</title>
    <script src="point-calc.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Check the Console</h1>
        <p>The results of the point calculations are displayed in the console.</p>
    </div>
</body>
</html>

JavaScript (point-calc.js)

This logic processes a shopping site point calculation, automatically using “1x” as the multiplier if none is specified.

/**
 * Function to calculate earned points
 * @param {number} purchaseAmount - Purchase amount (Mandatory)
 * @param {number} pointRate - Point multiplier (Defaults to 1.0)
 * @returns {number} Earned points
 */
const calculatePoints = (purchaseAmount, pointRate = 1.0) => {
    // If pointRate is omitted, 1.0 is used automatically
    const points = purchaseAmount * pointRate;
    return points;
};

// Pattern 1: Omitting the multiplier (Default value 1.0 is applied)
// Useful for standard member calculations
const standardPoints = calculatePoints(5000);
console.log(`When argument is omitted (Normal): ${standardPoints} pt`); // 5000 pt


// Pattern 2: Specifying the multiplier (The provided 3.0 is applied)
// Useful for campaigns or premium members
const campaignPoints = calculatePoints(5000, 3.0);
console.log(`When argument is specified (3x): ${campaignPoints} pt`); // 15000 pt

Customization Points

  • Modifying the Formula: While the example uses simple multiplication, setting a default to pointRate = 0 can turn a feature off when no option is provided.
  • Using Variables: It is possible to define a constant like const DEFAULT_RATE = 1.5; and set it as the default (pointRate = DEFAULT_RATE) to centralize the management of initial values.

Important Points

  • Handling of null and 0: Default values only trigger on undefined. If 0 is intentionally passed, as in calculatePoints(5000, 0), the value 0 is used instead of the default 1.0. Caution is required when determining whether a value exists.
  • Argument Order: Always place arguments with default values after mandatory arguments. Defining a function as function func(a = 1, b) makes passing a value only to b unnecessarily complex.

Advanced Usage

Generating Greeting Messages (String Operations)

Default parameters are also effective for optional string values.

// Example of making a title optional
const createGreeting = (userName, title = "-san") => {
    return `Hello, ${userName}${title}.`;
};

console.log(createGreeting("Sato"));           // Hello, Sato-san.
console.log(createGreeting("Tanaka", "-sensei")); // Hello, Tanaka-sensei.

Summary

Using default parameters removes the need for conditional branches like if (rate === undefined), resulting in significantly cleaner code. The primary rule is to place mandatory arguments first and optional arguments with default values at the end.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次