Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Các toán tử (Operators) trong JavaScript


Biểu thức đơn giản: 4 + 5 = 9. 4 và 5 là operands (toán hạng), + là operator (toán tử).

JavaScript hỗ trợ các loại toán tử:

  • Arithmetic (Số học): + - * / % ** (lũy thừa ES2016).
  • Comparison (So sánh): == === != !== > < >= <=.
  • Logical (Logic): && || ! ?? (nullish coalescing ES2020).
  • Assignment (Gán): = += -= *= /= %= **= <<= >>= >>>= &= ^= |= &&= ||= ??=.
  • Conditional/Ternary (Điều kiện): ? :.
  • Bitwise (Bit): & | ^ ~ << >> >>>.
  • String: + (concat), +=.
  • Type: typeof, instanceof, in, delete, new, await, yield.
  • Spread/Rest: ... (ES6).
  • Optional Chaining: ?. (ES2020).
  • Nullish Coalescing: ?? (ES2020).

Ví dụ minh họa

<html>
  <body>
    <script>
      var a = 33;
      var b = 10;
      var c = "Test";
      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); // "43Test"
      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>

Lưu ý quan trọng

  • Type Coercion: "5" + 3 = "53" (string concat), "5" - 3 = 2 (number). Luôn dùng === thay ==.
  • Operator Precedence: *, / trước +, -. Dùng ngoặc () để rõ ràng.
  • Short-circuit: &&, ||, ?? dừng sớm khi kết quả đã xác định.