JavaScript Functions: Declarations, Parameters, return
A function is a reusable block of code with a name, inputs (parameters) and an output (the return value). Functions are also values in JavaScript: you can store them in variables, pass them to other functions and return them. That idea powers the array methods and promises you will meet later.
Function declarations
function greet(name = "friend") { ... } declares a function named greet with one parameter. The = "friend" part is a default value, used when the caller passes nothing or passes undefined. Calling greet("Emma") runs the body with name set to "Emma".
return sends a value back and stops the function. If a function ends without return, or with a bare return;, the caller receives undefined, as noReturn() shows.
Rest parameters
A parameter written ...nums collects all remaining arguments into a real array, so sum(1, 2, 3, 4) works with any number of arguments. It must be the last parameter. Older code used the special arguments object for this; rest parameters replace it.
Expected output
Hello, Emma! Hello, friend! 10 81 undefined declarations are hoisted
Function expressions
const square = function (x) { return x * x; }; creates a function as part of an expression and stores it in a variable. It behaves like a declaration once defined, with one key difference: hoisting.
Hoisting
Function declarations are hoisted: the whole function is created before any code in its scope runs, which is why hoisted() can be called above the line that defines it. Function expressions assigned to const or let are not available before their line; calling them early throws a ReferenceError. Many teams define functions before using them anyway, for readability.
Arguments are passed by value
Primitives such as numbers and strings are copied into parameters, so changing a parameter does not affect the caller's variable. Objects and arrays are passed as references to the same object, so a function that pushes to an array parameter changes the caller's array.
Common mistakes
- Forgetting
return, then wondering why the result isundefined. - Putting
returnon its own line with the value on the next: automatic semicolon insertion ends the statement and returnsundefined. - Confusing
greet(the function value) withgreet()(calling it).
Summary
- Declare with
function name(params) { }; call withname(args). - Default parameters apply when an argument is missing or
undefined. ...restcollects extra arguments into an array.- Declarations are hoisted; function expressions are not.
Quiz: Functions