[JavaScript] Proper Use of the ‘let’ Declaration and How Reassignment Works

目次

Overview

In programming, a “variable” is like a box used to store data temporarily. Since the introduction of ES6 (Modern JavaScript), the keywords let and const are primarily used for variable declarations. This article focuses on let, which allows you to change (reassign) values later. We will explain basic handling, including declaration methods, updating values, and combining variables.

Specifications (Input/Output)

  • Input: Data such as strings, numbers, date objects, or functions.
  • Output:
    • Log output of variable declarations and initial values.
    • Confirmation of value changes through reassignment.
    • Output of calculation results combining multiple variables.

Basic Usage

To define a variable, use the syntax: let variableName = value;. Once a variable is declared with let, you can replace its contents (value) at any point in the program.

Full Code (HTML / JavaScript)

HTML (index.html)

This is the basic HTML structure used to check the results.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>let Variable Demo</title>
    <script src="variable-demo.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please open the console to check variables</h1>
        <p>Press F12 or right-click "Inspect" and select the Console tab.</p>
    </div>
</body>
</html>

JavaScript (variable-demo.js)

This code covers patterns for definition, reassignment, calculation, and concatenation.

/**
 * Demonstration of variable operations
 */
const runVariableDemo = () => {
    console.log('--- 1. Basic Declaration and Data Types ---');
    
    // Assigning a string
    let playerName = "Hero Alus";
    console.log("Name:", playerName);

    // Assigning an object (Date)
    let loginTimestamp = new Date();
    console.log("Login Time:", loginTimestamp);

    // Assigning a function (Arrow Function)
    let greetAction = () => console.log("Welcome to the game world!");
    greetAction(); // Execute the function stored in the variable

    
    console.log('--- 2. Reassigning Values (Updating) ---');
    
    // Changing the content of a variable
    // 'let' defines a variable that can be reassigned
    let currentStatus = "Status: Normal";
    console.log(currentStatus);
    
    currentStatus = "Status: Poisoned"; // Overwriting the value
    console.log(currentStatus);


    console.log('--- 3. Calculations Using Variables ---');

    // Numerical calculation
    let baseAttack = 50;
    let bonusAttack = 20;
    
    // Adding variables together and storing them in a new variable
    let totalAttack = baseAttack + bonusAttack;
    console.log("Total Attack Power:", totalAttack);


    console.log('--- 4. String Concatenation ---');

    // Joining variables that contain strings
    let lastName = "Sato";
    let firstName = "Ichiro";
    
    // Concatenating with the + operator
    let fullName = lastName + firstName;
    console.log("Full Name:", fullName);


    console.log('--- 5. Copying Values ---');

    // Copying a value from one variable to another
    let originalScore = 100;
    let copiedScore = originalScore;
    
    console.log("Copied Score:", copiedScore);
};

// Execute the demo
runVariableDemo();

Customization Points

  • Setting Initial Values: You can declare a variable without assigning a value, like let score; (the content will be undefined). This is used when you intend to assign a value later.
  • Changing to const: For variables that you do not plan to reassign (constants), using const instead of let is recommended. This tells others reading the code that the value will not change.
  • Variable Names: Keep your naming conventions consistent, such as user_name (snake_case) or userName (camelCase). In JavaScript, camelCase is the standard.

Important Points

  • Case Sensitivity: JavaScript variables are strictly case-sensitive. fullName and fullname are treated as two completely different variables. Typos leading to ReferenceError are very common.
  • Use After Declaration: You cannot use a variable before it is declared. Always declare your variable with let x = ... on a line above where you use it.
  • No Double Declarations: Writing let userName = ... twice within the same scope will cause an error. If you want to update the value, write userName = ... without the let keyword for the second time onwards.

Advanced Usage

Using Template Literals

When joining strings, using backticks () instead of the +` symbol allows you to embed variables more naturally.

let item = "Apple";
let price = 120;

// Traditional way
// let message = item + " is " + price + " yen.";

// Modern way (Template Literal)
let message = `${item} is ${price} yen.`;
console.log(message);

Summary

The let keyword is used to define variables where values can change flexibly. The basic steps are “Declaration,” “Assignment,” and “Reference.” However, reassigning values too often can make the program logic difficult to follow. Therefore, you should actively use const in places where values do not need to change.

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

この記事を書いた人

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

目次