ตัวดำเนินการทางคณิตศาสตร์พื้นฐานใน JavaScript ประกอบด้วย:
- ตัวดำเนินการทางคณิตศาสตร์ (Arithmetic Operators)
- ตัวดำเนินการเปรียบเทียบ (Comparison Operators)
- ตัวดำเนินการตรรกะ (Logical/Relational Operators)
- ตัวดำเนินการกำหนดค่า (Assignment Operators)
มาดูตัวดำเนินการทางคณิตศาสตร์ (Arithmetic operators) ว่าทำงานอย่างไรและประกอบด้วยอะไร:
| ลำดับ | ตัวดำเนินการและคำอธิบาย |
| 1 | + (บวก) บวกสองตัวถูกดำเนินการ ตัวอย่าง: A + B จะได้ 30 |
| 2 | - (ลบ) ลบตัวถูกดำเนินการที่สองออกจากตัวแรก ตัวอย่าง: A - B จะได้ -10 |
| 3 | * (คูณ) คูณทั้งสองตัวถูกดำเนินการ ตัวอย่าง: A * B จะได้ 200 |
| 4 | / (หาร) หารตัวเศษด้วยตัวส่วน ตัวอย่าง: B / A จะได้ 2 |
| 5 | % (มอดุลัส/เศษ) คืนค่าเศษจากการหารจำนวนเต็ม ตัวอย่าง: B % A จะได้ 0 |
| 6 | ++ (เพิ่มขึ้น) เพิ่มค่าจำนวนเต็มขึ้น 1 ตัวอย่าง: A++ จะได้ 11 |
| 7 | -- (ลดลง) ลดค่าจำนวนเต็มลง 1 ตัวอย่าง: A-- จะได้ 9 |
ตัวอย่าง
ลองรันโค้ดด้านล่างเพื่อเรียนรู้การทำงานของตัวดำเนินการทางคณิตศาสตร์ใน JavaScript
<html>
<body>
<script>
var a = 77;
var b = 30;
var c = "Demo";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
</script>
</body>
</html>