[JavaScript] Write Shorter Code with Compound Assignment Operators! A Guide to Efficient Calculations and Assignments

目次

Overview

When updating the value of a variable, a very common process is “add a number to the current value and put the result back into the same variable.”

Using JavaScript’s “compound assignment operators,” you can write these calculation and assignment processes in a shorter way. This makes your code easier to read.

This article explains how to use compound assignment operators for basic math like addition, subtraction, and multiplication, as well as for joining strings.

Specifications (Input/Output)

  • Input: A variable containing a number or a string.
  • Output: The new value after the calculation (displayed in the console log).

Basic Usage

A compound assignment operator is a shorthand that combines an operation (like +, -, or *) and an assignment (=) into one.

List of Compound Assignment Operators

OperatorSyntaxMeaning (Expanded Form)Example Use Case
=x = yx = ySimple assignment
+=x += yx = x + yAddition or string concatenation
-=x -= yx = x - ySubtraction (e.g., countdowns)
*=x *= yx = x * yMultiplication (e.g., multipliers)
/=x /= yx = x / yDivision (e.g., splitting values)
%=x %= yx = x % yModulus (e.g., finding remainders)
**=x **= yx = x ** yExponentiation (Power)

Full Code (HTML / JavaScript)

HTML (index.html)

This is the HTML file 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>Compound Assignment Operator Demo</title>
    <script src="assignment-demo.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please check the Console</h1>
        <p>The calculation results are displayed in the console.</p>
    </div>
</body>
</html>

JavaScript (assignment-demo.js)

This script demonstrates how each operator works using game stats and message construction as examples.

/**
 * Demo for using compound assignment operators
 */
const runAssignmentDemo = () => {
    console.log('--- 1. Addition Assignment with Numbers (+=) ---');
    
    let currentScore = 100;
    let bonusPoint = 50;
    
    // Same as: currentScore = currentScore + bonusPoint;
    currentScore += bonusPoint; 
    console.log(`Updated Score: ${currentScore}`); // 150


    console.log('--- 2. Addition Assignment with Strings (+=) ---');
    
    let greeting = "Hello, ";
    let userName = "Guest";
    
    // Same as: greeting = greeting + userName;
    // For strings, it attaches the new string to the end.
    greeting += userName; 
    console.log(`Message: ${greeting}`); // "Hello, Guest"


    console.log('--- 3. Multiplication Assignment (*=) ---');
    
    let attackPower = 20;
    let multiplier = 3;
    
    // Same as: attackPower = attackPower * multiplier;
    attackPower *= multiplier;
    console.log(`Attack Power: ${attackPower}`); // 60


    console.log('--- 4. Other Operators (/=, %=, **=) ---');
    
    let totalPizza = 8;
    // Cut in half
    totalPizza /= 2; 
    console.log(`Pizza remaining: ${totalPizza}`); // 4

    let loopCounter = 10;
    // Update to the remainder when divided by 3
    loopCounter %= 3; 
    console.log(`Remainder: ${loopCounter}`); // 1

    let baseNumber = 2;
    // Raise to the power of 3 (2 * 2 * 2)
    baseNumber **= 3;
    console.log(`2 to the power of 3: ${baseNumber}`); // 8
};

// Execute
runAssignmentDemo();

Customization Points

  • Variable Types: The += operator performs addition if the variable is a “number,” but performs string concatenation if it is a “string.” Be careful of accidental type conversion (for example, adding the number 5 to the string "10" results in "105").
  • Incrementing: If you only want to add 1, it is more common to use x++ (the increment operator) instead of x += 1.

Important Points

  • Not for const Variables: Since compound assignment operators perform “reassignment,” using them on a constant declared with const will cause an error (Assignment to constant variable). You must use let.
  • Forget to Initialize: If you try to perform an operation on an undefined variable (e.g., let x; x += 10;), the result will be NaN (Not a Number). Always set an initial value before use.
  • Side Effects: These operators rewrite the “actual value of the variable.” If you need to keep the original value, use a different variable and a standard calculation.

Advanced Usage

Generating HTML with Loops

The += operator is frequently used when looping through array data to join HTML strings together.

let htmlList = "<ul>";
const items = ["Item A", "Item B"];

items.forEach(item => {
    // Append list tags to the existing string
    htmlList += `<li>${item}</li>`;
});

htmlList += "</ul>";
console.log(htmlList); 
// <ul><li>Item A</li><li>Item B</li></ul>

Summary

Compound assignment operators (like +=, *=, etc.) are basic techniques to reduce redundant code and clarify the intent of updating a variable. In particular, += is very useful not only for math but also for building (concatenating) strings. Make sure you master how to use them.

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

この記事を書いた人

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

目次