Function Definitions
JavaScript has multiple syntaxes for the same thing. The differences in hoisting, this, and naming matter for picking the right one.
The forms at a glance
| Form | Syntax | Hoisted? | Own this? |
|---|---|---|---|
| Declaration | function fn() {…} | Yes (whole function) | Yes |
| Expression | const fn = function () {…} | Only the variable name | Yes |
| Named expression | const fn = function inner() {…} | Only the outer name | Yes — name visible inside for recursion |
| Arrow | const fn = () => {…} | No | No — inherits |
| Method shorthand | { fn() {…} } | — | Yes |
| Generator | function* fn() {…} | Yes | Yes |
| Async | async function fn() {…} | Yes | Yes |
new Function | new Function("a", "b", "return a+b") | — | Yes |
Picking by intent
JS
// Top-level helper — declaration (hoisted, nice in stack traces)
function debounce(fn, ms) { /* … */ }
// One-shot inline callback — arrow
button.addEventListener("click", () => render());
// Class / object method — shorthand
class Counter {
increment() { this.value++; }
}
// Recursive expression — named expression
const fact = function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); };
Tip: Function declarations show up in stack traces with their name. Anonymous expressions sometimes show as
<anonymous>. Name your top-level functions for easier debugging.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Function Definitions!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Mark a function as a generator.
function
counter() { let i = 0; while (true) yield i++; }
A single character — added immediately after `function`.
Discussion
Loading…