0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Arithmetic Operators in JavaScript: Simple Guide

In JavaScript, you use +, -, *, /, and % to perform basic math operations like addition, subtraction, multiplication, division, and remainder. These operators work with numbers and return the result of the calculation.
📐

Syntax

Arithmetic operators in JavaScript are symbols placed between two numbers (operands) to perform calculations. The basic operators are:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for division
  • % for remainder (modulus)

You write expressions like operand1 operator operand2. For example, 5 + 3 adds 5 and 3.

javascript
let sum = 5 + 3;
let difference = 10 - 4;
let product = 6 * 7;
let quotient = 20 / 5;
let remainder = 17 % 3;
💻

Example

This example shows how to use arithmetic operators to calculate and print results for addition, subtraction, multiplication, division, and remainder.

javascript
const a = 12;
const b = 5;

console.log('Addition:', a + b);       // 17
console.log('Subtraction:', a - b);    // 7
console.log('Multiplication:', a * b); // 60
console.log('Division:', a / b);       // 2.4
console.log('Remainder:', a % b);      // 2
Output
Addition: 17 Subtraction: 7 Multiplication: 60 Division: 2.4 Remainder: 2
⚠️

Common Pitfalls

One common mistake is using the + operator with strings, which causes concatenation instead of addition. Also, dividing by zero returns Infinity or -Infinity, which can cause bugs. Remember to use parentheses to control the order of operations.

javascript
const x = '5';
const y = 3;

// Wrong: adds string and number, results in string concatenation
console.log(x + y); // Output: '53'

// Right: convert string to number first
console.log(Number(x) + y); // Output: 8

// Division by zero
console.log(10 / 0); // Output: Infinity

// Use parentheses to change order
console.log(2 + 3 * 4);    // Output: 14
console.log((2 + 3) * 4);  // Output: 20
Output
53 8 Infinity 14 20
📊

Quick Reference

OperatorMeaningExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 742
/Division20 / 54
%Remainder17 % 32

Key Takeaways

Use +, -, *, /, and % to perform basic math operations in JavaScript.
Be careful with + operator as it concatenates strings if any operand is a string.
Division by zero returns Infinity, which is not an error but can cause logic issues.
Use parentheses to control the order of operations in complex expressions.
Convert strings to numbers before arithmetic to avoid unexpected results.