JavaScript Functions: Declarations, Expressions and Arrow Functions
The three main ways to define a function in JavaScript: declarations, function expressions and arrow functions. Hoisting, named function expressions, return values, arrow syntax rules and pitfalls, functions in blocks, nested functions, and which form to choose.
kvi5hnuCode Sprout team member8 min readOn this page
A function is a block of code you define once and run as many times as you like, each time with different inputs. Functions are how you name an idea ("calculate the shipping cost"), avoid repeating yourself, and break a big program into small pieces you can test. In JavaScript they're also values: you can store them in variables, pass them to other functions and return them, which is what makes callbacks, event handlers and array methods like map possible.
This part of the course covers functions in depth: defining them (this article), calling them and this, parameters, functions as values, closures, function methods like bind, and functional programming.
Three ways to define a function

function addDeclared(a, b) { // 1. function declaration
return a + b;
}
const addExpression = function (a, b) { // 2. function expression
return a + b;
};
const addArrow = (a, b) => a + b; // 3. arrow function
console.log(addDeclared(2, 3), addExpression(2, 3), addArrow(2, 3));
5 5 5
For simple calculations like this, all three behave the same. The differences, covered below, are in hoisting, this, arguments and new.
There are also method shorthand in objects and classes (article 52), getters and setters (article 53), generator functions function* (part 12), async functions (part 13) and the Function constructor (article 68).
Function declarations
A declaration starts with the function keyword and has:
- a name, which becomes a variable holding the function;
- a list of parameters in parentheses, which act as local variables;
- a body in braces, which runs each time the function is called.
function shippingCost(weightKg, express) {
const base = 4 + weightKg * 1.5;
return express ? base * 2 : base;
}
function logOrder(id) {
console.log(`order #${id} logged`); // no return statement
}
console.log(shippingCost(2, false), shippingCost(2, true));
console.log(logOrder(7));
7 14
order #7 logged
undefined
Return values
return stops the function and hands a value back to the caller. A function without return, or with a bare return;, returns undefined. Functions like logOrder exist for their side effects (printing, saving, updating the page), not for a result.
Remember automatic semicolon insertion (article 7): a line break right after return ends the statement, so the function returns undefined:
function config() {
return
{ debug: true };
}
console.log(config());
undefined
Keep the start of the returned expression on the same line as return, using parentheses if it spans several lines.
Hoisting
Function declarations are hoisted: the whole function is created before any code in its scope runs, so you can call it from earlier lines:
console.log(welcome("Ana"));
function welcome(name) {
return `Welcome, ${name}`;
}
Welcome, Ana
Many files use this to put the main logic at the top and helper functions at the bottom. (Variables declared with let and const are different: they exist from the start of the scope but can't be used before their line, the temporal dead zone of article 26.)
Function expressions
A function expression creates a function as part of a larger expression, typically assigned to a variable or passed as an argument. The name is optional:
const square = function (x) {
return x * x;
};
console.log(square(6));
console.log([3, 1, 2].sort(function (a, b) { return a - b; }));
36
[ 1, 2, 3 ]
Function expressions are not hoisted as functions. The variable follows its own rules (const/let: temporal dead zone; var: hoisted as undefined), so calling too early fails:
try {
tooSoon();
} catch (err) {
console.log(err.name); // const: still in the temporal dead zone
}
const tooSoon = function () {};
try {
alsoTooSoon();
} catch (err) {
console.log(err.name); // var: undefined is not a function
}
var alsoTooSoon = function () {};
ReferenceError
TypeError
Assign function expressions with const so the variable can't be accidentally reassigned to something else.
Named function expressions
A function expression can have its own name. That name is visible only inside the function, which is useful for recursion and makes stack traces clearer:
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5), typeof fact, factorial.name);
120 undefined fact
Using the inner name fact instead of the outer variable factorial means the recursion keeps working even if the outer variable is later reassigned.
Function names
Every function has a name property, used in stack traces and debugging. Anonymous functions assigned to a variable or property get that name automatically:
const anonymous = function () {};
const arrow = () => {};
const tools = { format() {} };
console.log(anonymous.name, arrow.name, tools.format.name);
console.log(JSON.stringify([(() => {}).name])); // no name to infer
anonymous arrow format
[""]
IIFEs
An expression can be called the moment it's created: an immediately invoked function expression (IIFE). Before block scope and modules, IIFEs were the standard way to keep variables private (article 66):
const tableSize = (function () {
const rows = 4, cols = 5; // not visible outside
return rows * cols;
})();
console.log(tableSize);
20
The surrounding parentheses make the parser read function as an expression; a statement can't start with an anonymous function.
Arrow functions
Arrow functions (ES2015) are a compact expression syntax: parameters, =>, then the body.
const add = (a, b) => a + b; // expression body: returned automatically
const double = n => n * 2; // one parameter: parentheses optional
const answer = () => 42; // no parameters: empty parentheses required
const describe = (name, age) => { // block body: needs return
const decade = Math.floor(age / 10) * 10;
return `${name} is in their ${decade}s`;
};
console.log(add(2, 3), double(4), answer(), describe("Bo", 34));
5 8 42 Bo is in their 30s
With an expression body, the value is returned automatically. With a block body in braces, you need return, just like a regular function. Forgetting it is the most common arrow-function bug (article 56).
Returning an object literal
Braces right after => always start a block body, so an object literal must be wrapped in parentheses:
const wrong = (x) => { value: x }; // a block with the label "value"
const right = (x) => ({ value: x });
console.log(wrong(1), right(1));
undefined { value: 1 }
In wrong, value: is parsed as a statement label (article 43) and x as an expression statement, so nothing is returned. With two properties, (x) => { a: x, b: x } is a SyntaxError, which at least tells you something is wrong.
No line break before the arrow
The => must be on the same line as the parameters. A line break before it is a SyntaxError. A line break after => is fine, and is how long arrow functions are usually formatted.
What arrow functions don't have
Arrow functions are deliberately lightweight. They don't have their own:
this: they use thethisof the surrounding code. That's their most important feature, explained in the next article.arguments: inside an arrow,argumentsrefers to the enclosing regular function's arguments. Use rest parameters (article 65) instead.prototype, so they can't be used withnew.
const Point = (x, y) => ({ x, y });
try {
new Point(1, 2);
} catch (err) {
console.log(err.name);
}
console.log(Point.prototype, typeof function () {}.prototype);
TypeError
undefined object
They also can't be generators (yield isn't allowed in them), though they can be async.
Nested functions
Functions can be defined inside other functions. An inner function can read and write the outer function's variables and parameters:
function hypotenuse(a, b) {
const square = (x) => x * x; // only visible inside hypotenuse
return Math.sqrt(square(a) + square(b));
}
console.log(hypotenuse(3, 4));
5
Nesting keeps helpers private to the only place that uses them. Combined with the ability to return the inner function, it leads to closures, one of JavaScript's most important features (article 67).
Functions in blocks
In strict mode and in modules, a function declared inside a block (if, loop body, { }) is scoped to that block, like let:
(function () {
"use strict";
if (true) {
function helper() {}
}
console.log(typeof helper);
})();
undefined
In sloppy-mode scripts, legacy browser rules (Annex B of the specification) also make the function visible outside the block, inconsistently between situations. Avoid declaring functions in blocks unless you're in strict mode or a module; use const helper = () => {} inside the block instead.
Which form should I use?
There's no single correct style, but these conventions are common:
- Declarations for named, top-level functions in a module: they're hoisted, easy to find, and read clearly (
function calculateTax(...)). - Arrow functions for callbacks and short functions:
items.map((item) => item.price), event handlers, promise chains. Theirthisbehavior is usually exactly what callbacks need. - Method shorthand for functions in objects and classes (
{ save() {...} }), not arrows, because methods need their ownthis. - Function expressions when you need a regular function as a value, such as a named recursive expression, or a callback that relies on its own
this.
Many teams enforce one style with ESLint's func-style and prefer-arrow-callback rules.
Common questions
Is there a performance difference between arrow and regular functions?
Not one that matters. Engines optimize both. Choose based on behavior (this, hoisting) and readability.
Are functions objects?
Yes. typeof reports "function", but functions are objects with properties (name, length) and methods (call, apply, bind). You can even add your own properties to them (article 66).
What happens if I declare two functions with the same name?
In a script, the later declaration silently replaces the earlier one, and both are hoisted, so every call uses the last one. In modules and with let/const, duplicates in the same scope are a SyntaxError, which is one more reason to prefer modules.
Can a function be called before an arrow function's definition line if it's only called later?
Yes: what matters is when the call runs, not where it's written. A declaration at the top can refer to an arrow function defined further down, as long as the call happens after that line has executed.
Summary
- Function declarations (
function name() {}) are hoisted, so they can be called before their line. - Function expressions create functions as values; they're usable only after the assignment runs. A name on an expression is visible only inside it, which helps recursion and stack traces.
- Functions without
return(or with a barereturn) returnundefined; don't put a line break right afterreturn. - Arrow functions are compact: expression bodies return automatically, block bodies need
return, and object literals need parentheses. - Arrows have no own
this,argumentsorprototype, and can't be used withnew. - Nested functions can use their outer function's variables; function declarations in blocks are block-scoped in strict code.
Practice Questions
What does this print?
console.log(typeof run, typeof go);
function run() {} var go = () => {};
Answer
function undefined. The declaration run is hoisted with its value; var go is hoisted but still undefined until its line runs.
Rewrite this code as an arrow function with an expression body.
function isEven(n) {
return n % 2 === 0;
}
Answer
const isEven = (n) => n % 2 === 0;
What does this code do, and how do you fix it?
const toPair = (k, v) => {
[k]: v
};
console.log(toPair("a", 1));
Answer
It's a SyntaxError: the braces start a block, and [k]: v isn't a valid statement. Wrap the literal in parentheses: (k, v) => ({ [k]: v }), which returns { a: 1 }.
Why might you give a function expression a name, as in this code?
const walk = function visit(node) {
...
}
Answer
The name visit is available inside the function for recursion, even if walk is reassigned later, and it appears in stack traces, which makes debugging easier.
Previous: JavaScript join, Array.isArray, Array-Like Objects and Strings as Arrays
Next: Calling JavaScript Functions: Methods, this, Constructors, Recursion and the Call Stack

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.