Syntax
function name(params) { /* body */ }
const name = function(params) { /* body */ };Examples
Calculate a total
Multiply two inputs and return a reusable result.
function total(price, quantity) {
return price * quantity;
}
console.log(total(12, 3));Function Declaration
A named function that can be called before its definition due to hoisting.
greet("Alice"); // works even though called before the definition below
function greet(name) {
console.log(`Hello, ${name}!`);
}Function Expression
Assigning an anonymous function to a variable - not hoisted.
const add = function(a, b) {
return a + b;
};
console.log(add(3, 4)); // 7
// Named function expressions are also possible, useful for stack traces
const multiply = function multiply(a, b) {
return a * b;
};Default and Return Values
Giving parameters default values and returning results.
function calculateTotal(price, taxRate = 0.1) {
return price + price * taxRate;
}
console.log(calculateTotal(100)); // 110 - uses default tax rate
console.log(calculateTotal(100, 0.2)); // 120 - overrides defaultBest practices
- Use function declarations for top-level, reusable functions you want available throughout a file regardless of definition order
- Use function expressions or arrow functions when defining a function inline (like a callback)
- Give parameters default values instead of manually checking for undefined inside the function body
- Keep functions focused on a single responsibility for easier testing and reuse
At a glance
- Purpose
- Application logic and interaction
- File extension
- .js · .mjs
- Runs in
- Browsers and JavaScript runtimes
- Usually used with
- HTML, CSS and Web APIs
In plain English
A function is a reusable operation. Parameters name its inputs, and return sends a result back to the caller.
What you’ll learn
- Declare and call a function.
- Pass arguments to parameters.
- Use a returned value.
Before you start: Variables: var, let, const
Breaking down the syntax
function- Introduces a function declaration.
parameters- Local names for values supplied by the caller.
return- Ends the call and supplies its result.
How it works
Arguments
The caller supplies input values.
Function body
The statements run with local parameter bindings.
Return value
A returned value can be assigned or passed onward. Falling off the end returns undefined.
When should I use this?
Use a function when an operation deserves a name, needs reuse, or should be tested separately.
Common mistakes
Printing instead of returning
console.log displays a value but does not return that value from your function.
Incorrect
function double(n) { console.log(n * 2); }
const result = double(3);Corrected
function double(n) { return n * 2; }
const result = double(3);
console.log(result);Compare approaches
- Function declaration: A named reusable operation with its own this binding rules.
- Arrow function: A concise expression with lexical this.
Accessibility
- Event-handler functions should support the native keyboard behaviour of the controls they enhance. Prefer a button to a clickable div.
Explore deeper
Inputs can reference mutable objects
Arguments are passed by value. When that value is an object reference, changing a property through the parameter affects the referenced object. Reassigning the parameter does not reassign the caller’s binding.
Specifications & further reading
Related JavaScript documentation
Arrow functions provide a more concise syntax for writing function expressions in JavaScript. Introduced in ES6, they use the => syntax and have some important differences from regular functions, particularly in how they handle the "this" keyword. Arrow functions are especially useful for callbacks, array methods, and short inline functions.Variables: var, let, const
JavaScript has three ways to declare variables. var is the original way, function-scoped and hoisted with a default value of undefined. let, introduced in ES6, is block-scoped and can be reassigned. const is also block-scoped but cannot be reassigned after its initial value is set. Modern JavaScript strongly favors let and const over var.Data Types
JavaScript has seven primitive data types - string, number, boolean, undefined, null, bigint, and symbol - plus the object type, which includes arrays, functions, and plain objects. JavaScript is dynamically typed, meaning a variable can hold any type and that type can change. The typeof operator reports a value's type at runtime.Arithmetic Operators
Arithmetic operators perform mathematical calculations on numbers: addition (+), subtraction (-), multiplication (*), division (/), remainder/modulo (%), and exponentiation (**). The + operator also performs string concatenation when either operand is a string. Increment (++) and decrement (--) adjust a variable by one.