The JavaScript function statement
A function is a reusable, named block of code that takes inputs (parameters) and can return a value. function add(a, b) { return a + b; } defines it; add(2, 3) calls it. Function declarations are hoisted, so you can call them before they appear. The compact arrow function is the modern alternative.
Overview
A function packages code you want to reuse. You define it once with parameters (the inputs) and call it as many times as you like with different arguments. Inside, the return statement sends a value back to the caller; with no return, a function gives back undefined. Functions are the fundamental unit of organization in JavaScript.
There are two main forms. A declaration, function greet() {}, is hoisted: the whole function is available throughout its scope, even above the line where it's written. An expression, const greet = function() {}, is assigned to a variable and is not usable before that line runs. The practical takeaway: you can call a declared function before its definition, but not a function expression.
Modern code leans heavily on the arrow function (const add = (a, b) => a + b), which is shorter and handles this differently: it inherits this from where it's defined, which is exactly what you want for callbacks. Functions also support default parameters (function f(x = 1)) and rest parameters (function f(...args)) for flexible signatures.
Syntax
// declaration (hoisted)
function add(a, b) {
return a + b;
}
// expression (not hoisted)
const sum = function (a, b) { return a + b; };
// arrow function
const plus = (a, b) => a + b;
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
function greet(name = 'friend') {
return 'Hello, ' + name + '!';
}
document.getElementById('out').textContent =
greet('Ada') + '\n' + greet(); // Hello, Ada! / Hello, friend!
</script>
Best practices
- Give functions clear, verb-based names and a single responsibility.
- Use return to send a result back; remember no
returnyieldsundefined. - Reach for arrow functions for callbacks, where their lexical
thisavoids bugs. - Use default parameters (
x = 1) and rest parameters (...args) for flexible, readable signatures.
Frequently asked questions
What is the difference between a function declaration and a function expression?
function f() {}) is hoisted and usable anywhere in its scope; an expression (const f = function() {}) only exists after its line runs.What is hoisting?
What is the difference between a regular function and an arrow function?
this from their surrounding scope, whereas regular functions get their own this based on how they're called.