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

Concise Arrow Function (Hàm mũi tên ngắn gọn) trong JavaScript


Concise arrow function: cú pháp (params) => expression. Không có function, không có {}, không có return (implicit return). 1 tham số có thể bỏ ().

Ví dụ

Hàm add concise:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Concise Arrow Function</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>Concise Arrow Function trong JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">TÍNH TỔNG</button>
  <h3>Nhấn nút để gọi add(32, 19) concise arrow</h3>
  <script>
    const resEle = document.querySelector(".result");
    const add = (a, b) => a + b;
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.textContent = `Tổng 32 + 19 = ${add(32, 19)}`;
    });
  </script>
</body>
</html>

Kết quả

Tổng 32 + 19 = 51.

Lưu ý: Nên trả về object literal phải bọc trong ngoặc đơn: () => ({a:1}).