iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

FormSyntaxHoisted?Own this?
Declarationfunction fn() {…}Yes (whole function)Yes
Expressionconst fn = function () {…}Only the variable nameYes
Named expressionconst fn = function inner() {…}Only the outer nameYes — name visible inside for recursion
Arrowconst fn = () => {…}NoNo — inherits
Method shorthand{ fn() {…} }Yes
Generatorfunction* fn() {…}YesYes
Asyncasync function fn() {…}YesYes
new Functionnew 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++; }

Test yourself

Q1. Which form is hoisted with its full body?
Q2. Named function expressions are useful for…
Q3. Generator function syntax is…

Discussion

Loading…