function
Declares a named function: a block of code with parameters that you can call any number of times and that can return a result.
Example
#function calculateLevel(points) {
return Math.floor(points / 100) + 1
}
console.log(calculateLevel(0))
console.log(calculateLevel(250))Definition and usage
#A function declaration creates a function with the given name. A function is a recipe wrapped in a block: it takes data through parameters, runs statements, and can return a result with return. Once written, you call it as many times as you like.
Parameters can have default values, used when an argument isn’t passed. The rest parameter ...rest collects all the extra arguments into an array. A function that never runs return returns undefined.
Function declarations are hoisted in full, so you can call a function higher up in the file than where it’s written. This doesn’t apply to function expressions, e.g. const add = function () {}, which only work from the line of assignment onward.
Syntax
#function name(param1, param2) {
// statements
return value
}
function name(param = defaultValue, ...rest) {}More examples
#function summary(student = 'Guest', ...scores) {
const total = scores.reduce((sum, score) => sum + score, 0)
return `${student}: ${total} pts`
}
console.log(summary('Emma', 10, 20, 30))
console.log(summary())console.log(double(21))
function double(n) {
return n * 2
}function applyBonus(points, rule) {
return rule(points)
}
function doubleBonus(points) {
return points * 2
}
console.log(applyBonus(40, doubleBonus))
console.log(applyBonus(40, (points) => points + 5))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Name functions with verbs that say what they do:
calculateTotal,formatDate,isValid. The code then reads almost like sentences. - A function should do one thing. If describing it needs the word “and,” consider splitting it into two smaller ones.
- Missing arguments get the value
undefined, and extra ones are ignored. JavaScript doesn’t report an error for the wrong number of arguments, so it’s worth validating the input.
Related entries
#- () => {} vs functionA regular function has its own this and arguments, is hoisted, and can be called with new. An arrow function is shorter and takes this from its surroundings.
- () => {}An arrow function: a shorter function syntax, with no own this, and an implicit return for a single expression.
- returnEnds a function and passes a value back to the place where the function was called.
- classDefines a class: a template for creating objects that share the same fields and methods.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
- DestructuringDestructuring pulls values out of arrays and objects straight into separate variables.
- function*Declares a generator: a function that hands back successive values through yield and pauses between them.
Spotted a mistake or missing an example? Write to us.