Sub topic 2
Function Declarations
This chapter assumes you know basic JavaScript syntax, can declare variables with var, let, and const, and have called functions with arguments before. It covers the function declaration: the oldest and most common way to define a named function in JavaScript. You will see how a declaration is parsed, what it creates, how a call runs, and which details tend to cause bugs.
Anatomy of a Declaration
A function declaration is a statement that starts with the function keyword, then a name, a parameter list in parentheses, and a body in braces.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5The parts are:
| Part | Example | Role |
|---|---|---|
| Keyword | `function` | Tells the parser a function definition starts here |
| Name | `add` | Required. Becomes a binding in the enclosing scope |
| Parameters | `(a, b)` | Local variables filled from the call's arguments |
| Body | `{ return a + b; }` | Code that runs on each call |
The name is required. function (a, b) { ... } on its own as a statement is a SyntaxError. The one exception is export default function () {} in a module, which is allowed to be anonymous.
What a Declaration Creates
A declaration does two things. It creates a function object, and it binds that object to the name in the surrounding scope. The function object is an ordinary value with properties of its own:
function add(a, b) {
return a + b;
}
console.log(typeof add); // "function"
console.log(add.name); // "add"
console.log(add.length); // 2name comes from the identifier in the declaration. length is the number of declared parameters, not counting a rest parameter or any parameter after the first one with a default value. The chapter on default and rest parameters covers those.
The binding works like a var binding, not like a const. You can reassign it:
function log(message) {
console.log(message);
}
log('first'); // first
log = function (message) {
console.log('[patched] ' + message);
};
log('second'); // [patched] secondThis is legal, and it is almost always a bug when it happens by accident. If you want a function name that cannot be reassigned, assign a function expression to a const. The next chapter covers that form.
Where Declarations Are Allowed
The parser decides whether function starts a declaration or an expression by its position. If a statement begins with the function keyword, it is a declaration. In any other position, such as after =, inside parentheses, or as an argument, it is an expression.
function a() { return 'declaration'; } // declaration
const b = function () { return 'expression'; }; // expression
(function c() { return 'expression'; }); // expression: wrapped in parentheses
console.log(a()); // declaration
console.log(b()); // expression
console.log(typeof c); // "undefined": c was never bound in this scopeThis position rule explains why c is not available afterward. Only declarations add their name to the enclosing scope. Declarations are meant for the top level of a script, module, or function body. Declarations placed inside if blocks and other blocks follow special rules, which a later chapter covers.
Because declarations are processed before the surrounding code runs, you can call a() from a line above its definition. The hoisting chapter explains exactly how that works and how it differs for expressions.
How a Call Runs
Each call to a declared function creates a fresh local scope. The engine binds the parameters to the arguments, runs the body, and hands back a value.
Argument count is not checked
JavaScript does not check how many arguments a call passes. Parameters without a matching argument become undefined, and extra arguments are not bound to any parameter.
function describe(name, role) {
return `${name} is a ${role}`;
}
console.log(describe('Ada', 'mathematician', 'extra')); // Ada is a mathematician
console.log(describe('Ada')); // Ada is a undefinedThe second call does not throw. The bad value only shows up later, in the output. When a parameter is optional, give it a default value or check for undefined explicitly.
Arguments are passed by sharing
JavaScript copies primitive arguments by value. For an object argument, it copies a reference to that object. Changing a property through the parameter affects the caller's object. Assigning a new object to the parameter does not.
function rename(user) {
user.name = 'Grace'; // mutates the caller's object
user = { name: 'Linus' }; // rebinds the local parameter only
return user.name;
}
const person = { name: 'Ada' };
console.log(rename(person)); // Linus
console.log(person.name); // GracePeople who expect either full copying or full reference semantics often get this wrong. If a function should not change its input, copy the input first, for example with { ...user } or structuredClone(user).
Each call has its own locals
Variables declared inside the body belong to that one call. Recursive or repeated calls do not share them.
function countdown(n) {
const label = `n=${n}`;
if (n === 0) {
return [label];
}
return [label, ...countdown(n - 1)];
}
console.log(countdown(3)); // [ 'n=3', 'n=2', 'n=1', 'n=0' ]Each level of recursion has its own label. Recursion works with a plain declaration because the name countdown is visible inside its own body through the enclosing scope.
Return Values
A function returns the value of the first return statement that runs. If the body finishes without one, or uses return; with no value, the call evaluates to undefined.
function sign(n) {
if (n > 0) return 'positive';
if (n < 0) return 'negative';
// falls through: returns undefined for 0 and NaN
}
console.log(sign(5)); // positive
console.log(sign(-1)); // negative
console.log(sign(0)); // undefinedEarly returns like these keep the body flat. Make sure every path returns something deliberate, though. The missing case for 0 is easy to miss.
function broken() {
return
{
debug: true
};
}
function fixed() {
return {
debug: true
};
}
console.log(broken()); // undefined
console.log(fixed()); // { debug: true }Redeclaration and Name Conflicts
Inside a function body or a classic script, a second declaration with the same name replaces the first, with no error. The last one in the source wins, even for calls written before it, because both are set up before any code runs.
function setup() {
function greet() { return 'first'; }
const early = greet();
function greet() { return 'second'; }
return early;
}
console.log(setup()); // secondThis silent overwrite can cause bugs when you join files or copy code between them. Some other conflicts are rejected at parse time:
| Situation | Result |
|---|---|
| Two function declarations, same name, in a function body or classic script | Allowed. The last one wins |
| Two function declarations, same name, at module top level | `SyntaxError` |
| `function x() {}` and `let x` or `const x` in the same scope | `SyntaxError` |
| `function x() {}` and `var x` in the same scope | Allowed. `var x;` without a value does not overwrite the function |
| Duplicate parameter names, `function f(a, a) {}`, in strict mode | `SyntaxError` |
Strict mode applies automatically in modules and class bodies, so the strict rows describe most modern code.
When a Declaration Is the Right Choice
Declarations are a good fit for named, top-level helpers in a module: functions you want to read like a list of named operations and call from anywhere in the file. The name is required and shows up in stack traces. Because declarations are hoisted, you can put the main logic first and the helpers below it.
Declarations are a poor fit when you need a function as a value in an expression, such as a callback, a function chosen at runtime, or a function whose binding must not be reassigned. The following chapters cover expressions and arrow functions for those cases, and the last chapter compares all the forms side by side.
Exercise
What does this program print, and why? function total(price, tax) { return price + price * tax; } console.log(total(100)); console.log(total(100, 0.2, 'ignored'));
Show answer
It prints NaN and then 120. In the first call tax is undefined, so price * tax is NaN, and 100 + NaN is NaN. In the second call the extra argument 'ignored' is not bound to any parameter, and the result is 100 + 20 = 120.
Exercise
A teammate writes the function below and reports that it always returns undefined. Explain the cause and fix it. function makeUser(name) { return { name: name, active: true }; }
Show answer
Automatic semicolon insertion adds a semicolon right after return because a line break follows it, so the function returns undefined. The braces on the next line are then parsed as a block statement, not an object literal. The fix is to start the object on the same line: return { name: name, active: true };
Exercise
Inside an ES module, a file contains function format() {} near the top and, after a merge, a second function format() {} near the bottom. What happens, and how would the same code behave in a classic browser script?
Show answer
In the module it is a SyntaxError at parse time, because top-level function declarations in a module cannot be duplicated, so none of the file runs. In a classic script both declarations are allowed, and the second replaces the first everywhere, including calls written above it. That overwrite produces no error.
Exercise
After rename(person) runs in the code below, what is person.name? function rename(user) { user = { name: 'B' }; user.name = 'C'; } const person = { name: 'A' };
Show answer
It is still 'A'. The first line rebinds the local parameter user to a new object, so the later property assignment changes that new object, not the caller's. The caller's object is never mutated.