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

Định nghĩa hàm (Function Definitions) trong JavaScript

Định nghĩa hàm bao gồm từ khóa function, tên hàm, tham số và khối lệnh trong cặp ngoặc nhọn.

Ví dụ

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    }    .sample {       font-size: 18px;       font-weight: 500;    } </style> </head> <body> <h1>Định nghĩa hàm trong JavaScript</h1> <div class="sample"></div> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để xem định nghĩa hàm</h3> <script>    let sampleEle = document.querySelector(".sample");    function helloWorld() {       alert("HELLO WORLD");    }    let testFunction = function () {       alert("TEST FUNCTION");    };    document.querySelector(".Btn").addEventListener("click", () => {       sampleEle.innerHTML = helloWorld + "<br>" + testFunction;    }); </script> </body> </html>

Kết quả

Hiển thị mã nguồn của hai hàm: function declaration và function expression.