[JavaScript] Robust Value Management and Reassignment Prevention with const

目次

Overview

In modern JavaScript (ES6 and later), const is the preferred choice for storing data. It defines a “constant,” which prevents a value from being reassigned once it has been set. This helps you avoid bugs caused by accidentally overwriting important values. This article explains how to use const in practical scenarios, such as defining configuration values or handling immutable objects.

Specifications (Input/Output)

  • Input: Fixed values like tax rates, product prices, or API endpoints.
  • Output:
    • Calculation results using constants.
    • Generated URLs from string concatenation.
    • Execution logs from functions defined as constants.

Basic Usage

When you declare a variable with const, you must set an initial value immediately. If you try to reassign a new value later (e.g., variableName = newValue), the browser will throw an error and stop execution. This keeps your data safe.

Full Code (HTML / JavaScript)

HTML (index.html)

This is the HTML file for testing the script.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>const Usage Demo</title>
    <script src="const-guide.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please check the system log</h1>
        <p>Calculation results and configuration values are output to the console.</p>
    </div>
</body>
</html>

JavaScript (const-guide.js)

This example manages values that should not change, such as price calculations and system settings, using const.

/**
 * Example of safe code design using constants (const).
 * This defines variables that cannot be reassigned.
 */
const runConstExample = () => {
    // 1. Numerical constants (Avoiding magic numbers)
    // It is common practice to use uppercase for fixed values like tax rates.
    const TAX_RATE = 0.1;
    const ITEM_PRICE = 2980;
    
    // Use const for calculation results if they won't change later.
    const taxAmount = ITEM_PRICE * TAX_RATE;
    const totalAmount = ITEM_PRICE + taxAmount;
    
    console.log(`Base Price: ${ITEM_PRICE} yen`);
    console.log(`Total Price (incl. tax): ${totalAmount} yen`);


    // 2. String constants and concatenation
    // Fixed strings like API paths.
    const API_BASE = "https://api.myservice.com";
    const API_VERSION = "v1";
    const ENDPOINT = "users";

    // Combine strings using template literals.
    const requestUrl = `${API_BASE}/${API_VERSION}/${ENDPOINT}`;
    console.log("Request URL:", requestUrl);


    // 3. Functions as constants
    // This prevents the function itself from being overwritten.
    const logSystemStatus = () => {
        const status = "OK";
        console.log(`System Status: ${status}`);
    };

    logSystemStatus();
};

// Execute
runConstExample();

Customization Points

  • Naming Conventions: Values that are absolutely fixed before the program starts (like TAX_RATE or physical constants) are usually written in UPPER_SNAKE_CASE. Values that are calculated but do not change afterward (like totalAmount) typically use standard camelCase.

Important Points

  • Immediate Initialization: You cannot declare a const without a value. Writing const myData; will cause a SyntaxError. You must write const myData = 10;.
  • Scope: Variables declared with const are block-scoped. If you declare one inside a block { ... } (like an if or for statement), you cannot access it from outside that block.
  • Object Properties: If you declare an object with const, like const config = { mode: "dark" };, you cannot reassign the variable to a new object (config = {};). However, you can change its properties, such as config.mode = "light";. To make an object completely unchangeable, use Object.freeze().

Advanced Usage

Full Immutability with Object.freeze()

This method makes even the properties inside an object unchangeable.

// Configuration object
const APP_CONFIG = Object.freeze({
    THEME_COLOR: "#FF5722",
    MAX_RETRY: 3
});

// The following line will be ignored (or throw an error in strict mode).
// APP_CONFIG.MAX_RETRY = 5; 

console.log(APP_CONFIG.MAX_RETRY); // Remains 3

Summary

When writing JavaScript, always try to use const first. Use let only when you absolutely need to change a value, such as with loop counters or toggle switches. Following this rule makes your code much easier to debug because you don’t have to track where a value might have changed.

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

この記事を書いた人

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

目次