Script Valley
JavaScript: The Complete Language
Functions and ScopeLesson 2.1

Function declarations vs function expressions vs arrow functions

function declaration, function expression, arrow function, hoisting of functions, anonymous functions, named function expressions, syntax differences

Three Ways to Write a Function

JavaScript has multiple function syntaxes. Each has trade-offs you need to know to read any real codebase.

Function Declaration

Hoisted entirely — you can call it before the line it appears.

greet("Ana"); // works — declaration is hoisted

function greet(name) {
  return "Hello, " + name;
}

Function Expression

Assigned to a variable. Not hoisted — the variable exists (undefined) but holds no function until that line runs.

const greet = function(name) {
  return "Hello, " + name;
};

const double = function double(n) { // named function expression
  return n * 2;
};

Arrow Function

Concise syntax introduced in ES6. No own this, no arguments object. Ideal for callbacks.

const greet = (name) => "Hello, " + name;
const square = n => n * n; // single param: parens optional
const noop = () => {};     // no params: parens required

// multi-line: needs return
const add = (a, b) => {
  const sum = a + b;
  return sum;
};

Which to Use

Use arrow functions for callbacks and short utilities. Use function declarations for top-level named functions you want hoisted. Use function expressions when you need a named self-referencing function.

Up next

Scope chain and lexical scope in JavaScript

Sign in to track progress