let price = 499;
let quantity = 3;
let subtotal = price * quantity;
// 1497
let tax = subtotal * 0.18;
// 269.46
let total = subtotal + tax;
// 1766.46
let perPerson = total / 4;
// 441.615 — splitting 4 ways
console.log(`Total: ₹${total}`);
// Total: ₹1766.46
console.log(`Each pays: ₹${perPerson}`);
// Each pays: ₹441.615JavaScript Arithmetic: Performing Mathematical Calculations with Operators
Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.
What is JavaScript Arithmetic? Core Concept & Direct Summary
What arithmetic operators and precision quirks exist in JavaScript?
Every app you love is secretly a math machine. Your food delivery total? Addition and multiplication. The "50% OFF" banner? Division. The "3 items left in stock" counter? Subtraction. Even that satisfying like-counter going from 99 → 100 is just+1with style.
The good news:JavaScript arithmetic is exactly the math you already know— plus a few special tricks. You met all operators briefly in this lesson, we go deep on the math side: every arithmetic operator, the order they run in, the powerfulMathobject, and how to defeat the infamous0.1 + 0.2bug once and for all.
Let's calculate. 🧮
How Does JavaScript Arithmetic Work? In-Depth Mechanics & Architecture
The 7 Arithmetic Operators (Complete Reference)
The Basics in Action
Congratulations — you just wrote the core logic of every shopping cart ever built. 🛒
Division: No Rounding Surprises
Unlike some languages, JavaScript divisionalways keeps decimals:
That last trio surprises programmers from other languages (where dividing by zero crashes the program). JavaScript just calmly answersInfinityorNaN.
⭐ The Modulus Operator (%) — The Hidden Superstar
%gives you theremainderafter division — and it's secretly one of the most useful operators in all of programming:
Real Uses You'll Actually Write
① Even or odd?(The interview classic)
② Every-Nth-item logic— "highlight every 3rd row":
③ Wrapping around— like a clock or a carousel:
If a problem involvescycles,remainders, orevery-Nth, the answer is almost always%.
The Exponent Operator (**) — Powers Made Easy
Introduced in 2016,**raises a number to a power:
💡Trick:x ** 0.5is a square root,x ** (1/3)is a cube root. No special function needed.
Increment (++) and Decrement (--) — The Counters
These add or subtract exactly 1 — you'll use them in every loop you ever write:
⚠️ Prefix vs Postfix: ++x vs x++
Placing++beforeorafterthe variable changeswhenthe value updates:
Beginner advice:in your first months, usex++on its own line and don't stress about the difference. You'll see it in loops constantly, where both behave identically.
Compound Assignment: The Shortcuts
Update a variable using its own current value — the shorthand family from Lesson 6, now in action:
Operator Precedence: What Calculates First? 🧮
When operators mix, JavaScript follows priority rules (like BODMAS from school):
Priority order (high → low):
()— parentheses always win**— exponents*/%— multiplication family (left to right)+-— addition family (left to right)
🏆 The professional habit:when in doubt,add parentheses.
total = (price * qty) - (price * qty * discount)is clearer than relying on precedence memory — and clear code has fewer bugs. Nobody has ever been criticized for too many parentheses in a calculation.The Math Object: JavaScript's Built-In Calculator
Beyond operators, JavaScript ships with a
Mathobject packed with tools. The daily essentials:🎲 The Famous Random Number Recipe
Math.random()alone gives decimals between 0 and 1. The classic combo for arandom whole number between 1 and 10:Memorize this pattern —
Math.floor(Math.random() * max) + 1— it appears in every game, quiz app, and raffle script ever written.🐛 The 0.1 + 0.2 Problem (And How to Fix It)
Time to face JavaScript's most famous math scandal:
Why?Computers store numbers in binary, and decimals like 0.1 have no exact binary representation — like how 1/3 = 0.333… never ends in decimal. Tiny rounding dust accumulates.This affects ALL programming languages, not just JavaScript.
The Fixes
①
toFixed()for displaying prices:② Work in the smallest unit (the professional way):
Banks and payment systems worldwide use this integer trick. No decimals, no dust, no bugs.
⚠️ Related danger:never compare float results with
===. Instead of0.1 + 0.2 === 0.3, check if they'reclose enough:Common Beginner Mistakes (And Fixes)
🛠️ Mini Project: Bill Splitter (Put It All Together!)
Output:
Multiplication, division, percentage math, and
toFixed()— four lesson concepts in one practical program. Try changing the values and watch it recalculate!Quick Self-Check: Lesson 12 Quiz 🧠
- What's the output?
console.log(17 % 5);- What's the output?
console.log(2 + 3 * 2 ** 2);- Write the one-liner that generates a random number from 1 to 100.
- Why does
0.1 + 0.2 === 0.3returnfalse?- What's the difference between
Math.floor(4.9),Math.ceil(4.1), andMath.round(4.5)?(Answers: 1.
2— 17 ÷ 5 = 3 remainder 2 · 2.14— exponent first (2²=4), then multiplication (3×4=12), then addition (2+12) · 3.Math.floor(Math.random() * 100) + 1· 4. Binary floating-point can't store 0.1 exactly — the sum is 0.30000000000000004 · 5. floor→4 (always down), ceil→5 (always up), round→5 (nearest)
JavaScript Decision Matrix & Syntax Comparison
Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.
var vs let vs const| Feature / Property | var (Legacy ES5) | let (Modern ES6+) | const (Modern ES6+) |
|---|---|---|---|
| Scope | Function Scope | Block Scope ({}) | Block Scope ({}) |
| Hoisting Behavior | Hoisted (initialized as undefined) | Hoisted (Temporal Dead Zone - ReferenceError) | Hoisted (Temporal Dead Zone - ReferenceError) |
| Reassignable | ✓ Yes | ✓ Yes | ✗ No (Immutable binding) |
| Redeclarable in Same Scope | ✓ Yes (Error-prone) | ✗ No (SyntaxError) | ✗ No (SyntaxError) |
| Window Object Binding | Creates property on window | Does not attach to window | Does not attach to window |
| Dimension | Client-Side (Web Browser) | Server-Side (Node.js / Deno) |
|---|---|---|
| Global Object | window, document, navigator | global, process, globalThis |
| DOM & UI Manipulation | ✓ Full access (document.querySelector) | ✗ No DOM (Headless / Non-UI) |
| File System & OS Access | ✗ Blocked (Sandboxed security) | ✓ Full access (fs, os, child_process) |
| Primary Focus | Interactive UI, animations, client state | REST APIs, microservices, databases, I/O streaming |
Runnable JavaScript Code Example & Practical Implementation
console.log(10 % 3);
// 1 (remainder)
console.log(2 ** 4);
// 16 (2 to the power 4)
console.log(0.1 + 0.2 === 0.3);
// false
console.log(Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON);
// trueFrequently Asked Questions & Technical Interview Insights
Technical Interview & Viva Questions
Frequently asked questions for frontend & full-stack rolesQ: How do pre-increment (++x) and post-increment (x++) differ?
Related Tools, Tutorials & Authoritative References
Recommended Interactive Tools
- Online JavaScript Editor & IDE — Browser-based JavaScript workspace with live console and DOM inspector.
- C Programming Tutorial — Master memory allocation, pointers, and systems programming fundamentals.
- C++ Programming Tutorial — Explore Object-Oriented Programming, templates, and high-performance STL.
- Online Code Editors & Compilers — Complete development tool suite for 20+ programming languages.
Authoritative Standards & Citations
- ECMA-262 ECMAScript Language Specification — The official international JavaScript language specification maintained by TC39.
- MDN Web Docs (Mozilla Developer Network) — Authoritative documentation and API guide for JavaScript and Web APIs.
- Google V8 JavaScript Engine — Open-source high-performance JavaScript and WebAssembly engine documentation.
- Node.js Official Documentation — Server-side JavaScript runtime API specification and reference.