Function Declaration / Function Expression
The basic syntax for defining functions in JavaScript. Both function declarations and function expressions define functions, but they differ in hoisting behavior and scope handling. You can write more flexible functions by combining default parameter values and rest parameters.
Syntax
// function declaration
function functionName(param1, param2) {
// body
return returnValue;
}
// Function expression (assigned to a variable)
var variableName = function(param1, param2) {
// body
return returnValue;
};
// Parameter with a default value
function functionName(param1, param2 /* = defaultValue */) {
if (param2 === undefined) {
param2 = defaultValue;
}
// body
}
// Rest parameters (ES2015 and later)
function functionName(param1, ...rest) {
// rest is received as an array.
}
function Declaration vs. Function Expression
| Feature | function declaration | Function expression |
|---|---|---|
| Hoisting | The entire function is hoisted. You can call it before the declaration. | Only the variable declaration is hoisted. Calling it before the assignment throws an error. |
| Name | A function name is required. | Anonymous functions are allowed (referenced via the variable name). |
| Best used for | Functions used throughout the script, such as those defined at the top level of a module. | Functions passed as callbacks, or when you want to assign different functions based on a condition. |
How Parameters Work
| Feature | Description |
|---|---|
| Omitting arguments | If you omit an argument when calling a function, that parameter receives undefined. |
| Default values | You can set a fallback value used when a parameter is undefined. In ES2015 and later you can write function f(x = 0), but in ES5 you check manually inside the function body. |
| Rest parameters | Prefixing the last parameter with ... collects all remaining arguments into an array (ES2015 and later). |
| arguments object | In ES5 and earlier environments, you can access all arguments inside a function through the array-like arguments object. |
| Return value (return) | The return statement returns a value. If omitted, the function returns undefined. |
Sample Code
function_hoisting.js
// Demonstrates hoisting with a function declaration.
// Calling the function before its declaration still works correctly.
// Called before the declaration (works due to hoisting).
var result1 = getUnitName(1);
console.log(result1); // "Unit-01"
// function declaration — hoisted to the top of the scope.
function getUnitName(unitNo) {
var units = ["Unit-00", "Unit-01", "Unit-02", "Unit-03"];
return units[unitNo] || "Unknown";
}
// A function expression cannot be called before its assignment.
// var result2 = getPilotName(0); // TypeError: getPilotName is not a function
var getPilotName = function(unitNo) {
var pilots = ["Rei Ayanami", "Shinji Ikari", "Asuka Langley Soryu"];
return pilots[unitNo] || "No pilot assigned";
};
console.log(getPilotName(0)); // "Rei Ayanami"
console.log(getPilotName(1)); // "Shinji Ikari"
Output
$ node function_hoisting.js Unit-01 Rei Ayanami Shinji Ikari
function_default_args.js
// Demonstrates default parameter values.
// Default values are applied inside the function when an argument is not passed (undefined).
function generateReport(pilotName, synchroRate, unitNo) {
// Use default values when arguments are omitted.
if (synchroRate === undefined) {
synchroRate = 0;
}
if (unitNo === undefined) {
unitNo = "Unknown";
}
return pilotName + " / Unit-" + unitNo + " / Sync rate: " + synchroRate + "%";
}
// All arguments provided
console.log(generateReport("Shinji Ikari", 41.3, 1));
// synchroRate and unitNo omitted (default values are used)
console.log(generateReport("Rei Ayanami"));
// unitNo omitted
console.log(generateReport("Asuka Langley Soryu", 75.2));
Output
$ node function_default_args.js Shinji Ikari / Unit-1 / Sync rate: 41.3% Rei Ayanami / Unit-Unknown / Sync rate: 0% Asuka Langley Soryu / Unit-Unknown / Sync rate: 75.2%
function_rest_params.js
// Demonstrates rest parameters and the arguments object.
// Rest params (ES2015 and later): prefixing the last parameter with "..." collects remaining arguments into an array.
function formTeam(leader, ...members) {
// members is received as an array.
console.log("Leader: " + leader);
console.log("Member count: " + members.length);
for (var i = 0; i < members.length; i++) {
console.log(" " + (i + 1) + ". " + members[i]);
}
}
formTeam("Misato Katsuragi", "Shinji Ikari", "Rei Ayanami", "Asuka Langley Soryu");
console.log("---");
// arguments object (works in ES5 and earlier environments)
function listPilots() {
// arguments is an array-like object (Array methods are not available).
for (var i = 0; i < arguments.length; i++) {
console.log("Pilot " + (i + 1) + ": " + arguments[i]);
}
}
listPilots("Shinji Ikari", "Rei Ayanami", "Kaworu Nagisa");
Output
$ node function_rest_params.js Leader: Misato Katsuragi Member count: 3 1. Shinji Ikari 2. Rei Ayanami 3. Asuka Langley Soryu --- Pilot 1: Shinji Ikari Pilot 2: Rei Ayanami Pilot 3: Kaworu Nagisa
function_assign_variable.js
// Demonstrates assigning a function to a variable.
// You can assign different functions to the same variable based on a condition.
var mode = "battle"; // "battle" or "eva-maintenance"
// Assign a different function depending on the condition.
var execute;
if (mode === "battle") {
execute = function(unitNo) {
return "Unit-" + unitNo + " launching!";
};
} else {
execute = function(unitNo) {
return "Unit-" + unitNo + " maintenance complete.";
};
}
console.log(execute(1));
console.log(execute(2));
// Passing a function as a callback
var unitNos = [0, 1, 2];
var reports = unitNos.map(function(no) {
return "Unit-" + no + ": sync check complete";
});
for (var i = 0; i < reports.length; i++) {
console.log(reports[i]);
}
Output
$ node function_assign_variable.js Unit-1 launching! Unit-2 launching! Unit-0: sync check complete Unit-1: sync check complete Unit-2: sync check complete
Notes
A function declaration is hoisted to the top of its scope, so you can call it before the declaration and it will work correctly. A function expression, on the other hand, is treated as a variable assignment, so calling it before the assignment throws a TypeError. Code that relies on hoisting can be harder to read, so it is a good habit to define functions before calling them.
If you call a function without passing an argument, that parameter receives undefined. To set a default value, the standard ES5 approach is to check if (param === undefined) inside the function body. In ES2015 and later, you can write = value directly in the parameter list. For variadic arguments, use rest parameters (prefix the last parameter with ..., ES2015 and later) or the arguments object available in older environments.
Assigning a function to a variable is commonly used for callbacks and for switching between different functions based on a condition. A function stored in a variable can be called through that variable or passed as an argument to another function. Passing an anonymous function expression to Array.forEach() or Array.map() as a callback is a typical example.
Browser Compatibility
3 and earlier ×
3 and earlier ×
Android Browser
37+ ○
4 and earlier ×
Chrome Android
36+ ○
17 and earlier ×
Firefox Android
79+ ○
3 and earlier ×If you find any errors or copyright issues, please contact us.