Khái niệm
Toán tử nhóm ( ) kiểm soát thứ tự ưu tiên (precedence) của phép toán, ép buộc đánh giá biểu thức bên trong trước.
Ví dụ minh họa
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grouping Operator</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
.sample, .result { font-size: 16px; font-weight: 500; margin: 10px 0; padding: 15px; border-radius: 4px; }
.sample { color: #d32f2f; background: #ffebee; }
.result { color: #6a1b9a; background: #f3e5f5; }
button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<h1>Toán tử nhóm (Grouping Operator) trong JavaScript</h1>
<div class="sample" id="sample">2+2*5/22</div>
<div class="result" id="result"></div>
<button id="btn">TÍNH TOÁN VỚI NHÓM</button>
<h3>Nhấn nút để dùng nhóm chỉ định thứ tự ưu tiên</h3>
<script>
const sampleEle = document.getElementById('sample');
const resultEle = document.getElementById('result');
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
resultEle.innerHTML = '';
// Mặc định: * / trước + -
resultEle.innerHTML += `2+2*5/22 = ${2 + 2 * 5 / 22}<br>`;
// = 2 + (10/22) = 2 + 0.4545 = 2.4545
// Nhóm (2+2) trước
resultEle.innerHTML += `(2+2)*5/22 = ${(2 + 2) * 5 / 22}<br>`;
// = 4*5/22 = 20/22 = 0.909
// Nhóm (2+2*5) trước
resultEle.innerHTML += `(2+2*5)/22 = ${(2 + 2 * 5) / 22}<br>`;
// = (2+10)/22 = 12/22 = 0.545
});
</script>
</body>
</html>
Kết quả
2+2*5/22 = 2.4545454545454546 (2+2)*5/22 = 0.9090909090909091 (2+2*5)/22 = 0.5454545454545454
Bảng ưu tiên toán tử (Precedence) - Từ cao đến thấp
| Độ ưu tiên | Toán tử | Ví dụ |
|---|---|---|
| 21 (Highest) | Grouping | (...) |
| 20 | Member Access, Computed Member, new, Function Call | obj.prop, arr[i], new Fn(), fn() |
| 17 | Postfix | i++, i-- |
| 16 | Prefix | ++i, --i, !, ~, +, -, typeof, void, delete |
| 15 | Exponentiation | ** |
| 14 | Multiplicative | *, /, % |
| 13 | Additive | +, - |
| 12 | Bitwise Shift | <<, >>, >> |
| 11 | Relational | <, <=, >, >=, in, instanceof |
| 10 | Equality | ==, !=, ===, !== |
| 9 | Bitwise AND | & |
| 8 | Bitwise XOR | ^ |
| 7 | Bitwise OR | | |
| 6 | Logical AND | && |
| 5 | Logical OR | || |
| 4 | Nullish Coalescing | ?? |
| 3 | Conditional (Ternary) | ? : |
| 2 | Assignment | =, +=, -=, **=, ... |
| 1 (Lowest) | Comma | , |
Ứng dụng thực tế
1. IIFE (Immediately Invoked Function Expression)
(function() {
// Private scope
})();
// Arrow function IIFE
(() => {
// ...
})();
2. Arrow function return object literal
// ❌ Sai - {} được hiểu là block
const fn = () => { a: 1 }; // undefined
// ✅ Đúng - nhóm ()
const fn = () => ({ a: 1 }); // {a: 1}
3. Destructuring assignment không khai báo
let a, b;
({ a, b } = { a: 1, b: 2 }); // Cần () bao quanh
4. Optional chaining với grouping
const result = (obj?.prop?.method?.() ?? 'default').toUpperCase();