JavaScript coi hàm như đối tượng (first-class functions): có thể truyền hàm làm tham số, trả về hàm từ hàm khác, lưu hàm trong biến/obj/array. Higher-order functions có thể nhận hàm, trả về hàm, hoặc cả hai.
Ví dụ
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>First class function</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .result { color: red; } </style> </head> <body> <h1>First-class function trong JavaScript</h1> <div class="sample">[22,33,44,55]</div> <br /> <div class="result"></div> <br /> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để gấp đôi từng phần tử của mảng trên</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let doubleNum = (ele) => { return ele * 2; }; let arr = [22, 33, 44, 55]; function doubleArray(arr, fn) { let doubleArr = []; arr.forEach((element) => { doubleArr.push(doubleNum(element)); }); return doubleArr; } BtnEle.addEventListener("click", () => { resEle.innerHTML = "New array = " + doubleArray(arr, doubleNum); }); </script> </body> </html>
Kết quả
Khi nhấn nút: New array = 44,66,88,110
doubleNum là first-class function (arrow function gán cho biến). doubleArray là higher-order function nhận fn làm tham số. Đây là nền tảng của functional programming: map, filter, reduce, compose, pipe, currying, partial application.