[JavaScript] Complete Guide to Numerical Calculation using Arithmetic Operators

目次

Overview

Numerical calculation is one of the most basic and important processes in programming. In JavaScript, besides standard arithmetic like addition and subtraction, there are specific operators for finding the remainder (modulus) and raising a number to a power (exponentiation). This article explains the behavior of these six arithmetic operators and provides code examples for practical use.

Specifications (Input/Output)

  • Input: Two defined numerical values.
  • Output:
    • Results of addition, subtraction, multiplication, division, modulus, and exponentiation.
    • Log output displayed in the browser console.

Basic Usage

In JavaScript, calculations are performed by placing the following operator symbols between numbers.

Arithmetic Operator List

OperatorMeaningExampleResult (a=10, b=3)
+Additiona + b13
Subtractiona – b7
*Multiplicationa * b30
/Divisiona / b3.333…
%Modulus (Remainder)a % b1
**Exponentiation (Power)a ** b1000 (10³)

Full Code (HTML / JavaScript)

HTML (index.html)

This screen prompts you to check the console for calculation results.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Operator Demo</title>
    <script src="calc-demo.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Check Calculation Results</h1>
        <p>Results are output to the browser's developer tools (console).</p>
        <p>Press F12 and open the "Console" tab.</p>
    </div>
</body>
</html>

JavaScript (calc-demo.js)

This logic uses the six main operators. It outputs both the formula and the result for better readability.

/**
 * Demonstration function for arithmetic operators
 */
const performCalculations = () => {
    // Numbers used for calculation
    const numA = 8;
    const numB = 3;

    console.log(`--- Starting Calculation: A=${numA}, B=${numB} ---`);

    // 1. Addition (+)
    const sum = numA + numB;
    console.log('Addition (+):', sum);

    // 2. Subtraction (-)
    const difference = numA - numB;
    console.log('Subtraction (-):', difference);

    // 3. Multiplication (*)
    const product = numA * numB;
    console.log('Multiplication (*):', product);

    // 4. Division (/)
    const quotient = numA / numB;
    console.log('Division (/):', quotient);

    // 5. Modulus (%) - Remainder of a division
    // Use cases: Checking for even/odd numbers, detecting specific intervals in loops, etc.
    const remainder = numA % numB;
    console.log('Modulus (%):', remainder);

    // 6. Exponentiation (**) - Added in ES2016
    // Equivalent to Math.pow(numA, numB)
    const power = numA ** numB;
    console.log('Exponentiation (**):', power);
};

// Run the calculations
performCalculations();

Customization Points

  • Changing Variables: Try changing the values of numA and numB to see how the results change with decimals or negative numbers.
  • Displaying on Screen: Currently, the script uses console.log. You can change this to document.body.innerHTML += ... if you want to display results directly on the web page.

Important Points

  • Floating Point Errors: Due to how JavaScript handles numbers, calculations with decimals (e.g., $0.1 + 0.2$) might result in small errors like $0.30000000000000004$ instead of exactly $0.3$. Be careful when handling precise values like money.
  • String Concatenation: If one side of the + operator is a string, it acts as a “connector” instead of an adder (e.g., $10 + “20”$ becomes $”1020″$). Always ensure your data is a number type for math.
  • Division by Zero: Dividing a number by $0$ returns a special value called Infinity instead of an error. It is best to check that the divisor is not zero to avoid unexpected behavior.

Advanced Usage

Using Compound Assignment Operators

You can use shorthand when updating a variable’s value through a calculation.

let score = 100;

// Same as score = score + 50
score += 50; 
console.log(score); // 150

// Same as score = score * 2
score *= 2;
console.log(score); // 300

Summary

These operators are the foundation of programming. However, JavaScript has specific characteristics like string concatenation and decimal errors that you must watch for. In particular, the modulus operator (%) is frequently used in logic for repeating tasks at intervals or keeping numbers within a certain range, so it is important to understand how it works.

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

この記事を書いた人

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

目次