Skip to content
  • Functions: Declarations, Expressions & Arrows · JavaScript

Functions: Declarations, Expressions & Arrows

LearnViaNotes @learnvianotes· 2 min read

Functions are first-class objects: create them three ways, pass them around, return them — and pick arrows or regular functions for the right reasons.

Three ways to define a function

JavaScript
// 1. Declaration — hoisted completely
function add(a, b) {
  return a + b;
}
// 2. Expression — a value assigned to a variable (optionally named)
const multiply = function mul(a, b) {
  return a * b;
};
// 3. Arrow function (ES2015) — concise, lexical `this`
const square = (x) => x * x;
const makePoint = (x, y) => ({ x, y });   // wrap object literals in ( )

console.log(add(2, 3), multiply(2, 3), square(4), makePoint(1, 2));
console.log(multiply.name, square.name, add.length);
Output
5 6 16 { x: 1, y: 2 }
mul square 2

Declarations are hoisted, expressions are not

JavaScript
console.log(early());          // works: whole declaration is hoisted
function early() { return "declared"; }

try {
  late();
} catch (e) {
  console.log(e.name + ": " + e.message);
}
const late = () => "expression";
Output
declared
ReferenceError: Cannot access 'late' before initialization

Arrow vs regular functions

Regular functionArrow =>
thisSet by how it is calledInherited from the enclosing scope (lexical)
argumentsYesNo (use rest ...args)
Can be used with newYesNo — TypeError
prototype propertyYesNo
HoistingDeclarations are hoistedLike any const — TDZ
Best forMethods, constructors, generatorsCallbacks, short transforms, keeping outer this
JavaScript
const Arrow = () => {};
try {
  new Arrow();
} catch (e) {
  console.log(e.message);
}
console.log(Arrow.prototype, typeof function () {}.prototype);
Output
Arrow is not a constructor
undefined object

Functions are objects

JavaScript
function greet(name) { return `Hi ${name}`; }
greet.calls = 0;                       // attach properties like any object
const fns = [greet, (s) => s.toUpperCase()];
console.log(fns.map((f) => f("x")));
console.log(typeof greet, greet instanceof Object, greet);
Output
[ 'Hi x', 'X' ]
function true [Function: greet] { calls: 0 }

Return values

  • A function without return (or with a bare return;) returns undefined.

  • Arrow with a concise body (x => x * 2) returns the expression; with braces you need return.

  • Automatic semicolon insertion: return followed by a newline returns undefined — keep the value on the same line.

JavaScript
function broken() {
  return
    { ok: true };
}
const withBraces = (x) => { x * 2 };
console.log(broken(), withBraces(2));
Output
undefined undefined

What is the difference between a function declaration and a function expression?

When should you NOT use an arrow function?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report