JavaScript มีตัวดำเนินการ (Operators) หลายประเภท เช่น Arithmetic, Assignment, Comparison, Logical, Bitwise, String, Ternary, typeof เป็นต้น แต่ละแบบใช้สำหรับงานเฉพาะ เช่นคำนวณทางคณิตศาสตร์, เปรียบเทียบค่า, กำหนดค่า, หรือเชื่อมข้อความ.
ใช้สำหรับการคำนวณตัวเลข
ตัวอย่าง:
let x = 5, y = 2;
console.log(x + y); // 7
console.log(x % y); // 1
ใช้กำหนดค่าให้ตัวแปร:
ตัวอย่าง:
let x = 10;
x += 5; // x = 15
ใช้เปรียบเทียบค่า คืนค่าเป็น true หรือ false:
ตัวอย่าง:
console.log(5 == "5"); // true
console.log(5 === "5"); // false
ใช้เชื่อมเงื่อนไข:
ตัวอย่าง:
let a = true, b = false;
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false
ทำงานกับค่าบิตโดยตรง:
let name = "John";
console.log("Hello " + name); // Hello John
ใช้เขียนเงื่อนไขสั้น ๆ:
let age = 18;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // Adult
ใช้ตรวจสอบชนิดข้อมูล:
console.log(typeof 123); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
| ประเภท Operator | ตัวอย่าง | ผลลัพธ์ |
|---|---|---|
| Arithmetic | 5+2 | 7 |
| Assignment | x += 3 | เพิ่มค่าใน x |
| Comparison | 5 === "5" | FALSE |
| Logical | true || false | TRUE |
| Bitwise | 5 &1 | 1 |
| String | "Hi" + "!" | "Hi!" |
| Ternary | x > 10 ? "Yes":"No" | "Yes" หรือ "No" |
| typeof | typeof 123 | "number" |
Operators คือเครื่องมือหลักใน JavaScript ที่ช่วยให้เราทำงานกับค่าต่าง ๆ ได้สะดวก ทั้งการคำนวณ, การเปรียบเทียบ, การเชื่อมข้อความ และการตรวจสอบชนิดข้อมูล.