JavaScript: Functions
JavaScript Functions
1 Overview
📘 Functions
Functions are the main “building blocks” of programs. They allow code to be called many times without repetition. Functions can accept parameters (inputs), perform actions, and return values (outputs). JavaScript supports multiple ways to define functions: function declarations, function expressions, and arrow functions. Functions help organize code, make it reusable, and improve maintainability.
2 Function Declaration
To create a function, we can use a function declaration:
The function
keyword goes first, then the name of the function, then a list of parameters between parentheses (comma-separated), and finally the function body between curly braces.
2.1 Syntax
2.2 Calling a Function
Our new function can be called by its name:
The call showMessage()
executes the code of the function.
3 Local Variables
A variable declared inside a function is only visible inside that function.
4 Outer Variables
A function can access an outer variable as well:
4.1 Modifying Outer Variables
The function has full access to the outer variable and can modify it:
4.2 Variable Shadowing
If a same-named variable is declared inside the function, it shadows the outer one:
4.3 Global Variables
Variables declared outside of any function are called global.
Global variables are visible from any function (unless shadowed by locals).
Best Practice: Minimize the use of global variables. Modern code has few or no globals. Most variables should reside in their functions.
5 Parameters
We can pass arbitrary data to functions using parameters.
When the function is called, the given values are copied to local variables from
and text
.
5.1 Parameters vs Arguments
- Parameter: The variable listed inside the parentheses in the function declaration (declaration time)
- Argument: The value that is passed to the function when it is called (call time)
5.2 Parameters are Copied
A function always gets a copy of the value:
6 Default Values
If a parameter is not provided, its value becomes undefined
.
6.1 Setting Default Values
We can specify a default value using =
:
6.2 Default Value Expressions
The default value can be a more complex expression:
6.3 Alternative Default Parameters
Old JavaScript code might use alternative ways to check for default values:
Or using the ||
operator:
Modern approach with nullish coalescing ??
:
7 Returning a Value
A function can return a value back into the calling code as the result.
The directive return
can be in any place of the function. When execution reaches it, the function stops, and the value is returned.
7.1 Multiple Returns
There may be many occurrences of return
in a single function:
7.2 Return Without a Value
It’s possible to use return
without a value to exit immediately:
7.3 Empty Return Returns undefined
If a function does not return a value, it returns undefined
:
An empty return
is also the same as return undefined
:
Never add a newline between return and the value
JavaScript assumes a semicolon after return
, so this becomes:
If you want to wrap the returned expression across multiple lines, start it on the same line as return
:
8 Function Expressions
A Function Expression allows us to create a function in the middle of any expression.
Here, the function is created and assigned to the variable explicitly, like any other value.
8.1 Function is a Value
No matter how the function is created, a function is a value. We can copy it to another variable:
9 Function Declaration vs Function Expression
9.1 Function Declaration
- Can be called earlier than it is defined (hoisting)
- Block-scoped in strict mode
9.2 Function Expression
- Created when execution reaches it
- Can only be called after it’s defined
9.3 Example: Hoisting
10 Arrow Functions
Arrow functions provide a shorter syntax for writing function expressions:
10.1 Arrow Function Syntax
// Single parameter, no parentheses needed
let double = n => n * 2;
alert(double(3)); // 6
// Multiple parameters, parentheses required
let sum = (a, b) => a + b;
alert(sum(1, 2)); // 3
// No parameters, empty parentheses
let sayHi = () => alert("Hello!");
sayHi();
// Multiline arrow function, explicit return
let sum = (a, b) => {
let result = a + b;
return result;
};
11 Naming Functions
Functions are actions, so their name is usually a verb. It should be brief, as accurate as possible, and describe what the function does.
11.1 Common Prefixes
"get…"
– return a value"calc…"
– calculate something"create…"
– create something"check…"
– check something and return a boolean
Examples:
11.2 One Function – One Action
A function should do exactly what is suggested by its name, no more.
Two independent actions usually deserve two functions, even if they are usually called together.
Bad examples: - getAge
– would be bad if it shows an alert
with the age (should only get) - createForm
– would be bad if it modifies the document (should only create and return) - checkPermission
– would be bad if it displays the access granted/denied message (should only check)
12 Examples
12.1 Example 1: Simple Function
12.2 Example 2: Function with Multiple Parameters
12.3 Example 3: Function with Default Parameters
12.4 Example 4: Function Returning Boolean
12.5 Example 5: Function with Early Return
12.6 Example 6: Calculator Functions
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
}
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
console.log(multiply(5, 3)); // 15
console.log(divide(6, 3)); // 2
console.log(divide(5, 0)); // Cannot divide by zero
12.7 Example 7: Arrow Functions
// Traditional function
function square(x) {
return x * x;
}
// Arrow function
const squareArrow = x => x * x;
console.log(square(5)); // 25
console.log(squareArrow(5)); // 25
// Multiple parameters
const add = (a, b) => a + b;
console.log(add(3, 4)); // 7
// Multiline arrow function
const greet = name => {
let message = `Hello, ${name}!`;
return message;
};
console.log(greet("Alice")); // Hello, Alice!
12.8 Example 8: Function as Value
13 Summary
- Functions are declared with the
function
keyword - Functions can have parameters (inputs) and return values (outputs)
- Variables declared inside a function are local to that function
- Functions can access outer variables and modify them
- Use descriptive names for functions (verbs that describe the action)
- One function should do one thing
- Function Declarations are hoisted (can be called before declaration)
- Function Expressions are created when execution reaches them
- Arrow functions provide a shorter syntax:
(a, b) => a + b
- Default parameter values can be specified with
=
return
without a value returnsundefined
- Functions are values and can be assigned to variables or passed as arguments