JavaScript Function Parameters
Learn the basics of JavaScript Function Parameters.
A function in JavaScript can accept one or more parameters. Let’s look at some examples:
1 | const doSomething = () => { |
Starting from ES6/ES2015, functions can have default values for their parameters. Here’s an example:
1 | const doSomething = (foo = 1, bar = 'hey') => { |
This allows you to call the function without specifying all the parameters:
1 | doSomething(3); |
In ES2018, trailing commas for parameters were introduced. This feature helps reduce bugs due to missing commas when rearranging parameters:
1 | const doSomething = (foo = 1, bar = 'hey',) => { |
It is also okay to call your functions with a trailing comma after the last parameter:
1 | doSomething(2, 'ho!',); |
You can also wrap all your arguments in an array and use the spread operator when calling the function:
1 | const doSomething = (foo = 1, bar = 'hey') => { |
With many parameters, it can be difficult to remember their order. By using objects and destructuring, you can keep the parameter names:
1 | const doSomething = ({ foo = 1, bar = 'hey' }) => { |
Functions also support default parameters:
1 | const foo = function(index = 0, testing = true) { /* ... */ } |
Default parameter values were introduced in ES2015 and are widely implemented in modern browsers.
Here’s an example of a doSomething
function that accepts param1
:
1 | const doSomething = (param1) => { |
You can add a default value for param1
if the function is invoked without specifying a parameter:
1 | const doSomething = (param1 = 'test') => { |
This works for multiple parameters as well:
1 | const doSomething = (param1 = 'test', param2 = 'test2') => { |
What if you have a unique object with parameter values in it? In the past, if we had to pass an object of options to a function and have default values for those options if they were not defined, we had to add some code inside the function:
1 | const colorize = (options) => { |
With object destructuring, you can provide default values, which simplifies the code significantly:
1 | const colorize = ({ color = 'yellow' }) => { |
If no object is passed when calling the colorize
function, you can assign an empty object as the default:
1 | const spin = ({ color = 'yellow' } = {}) => { |
tags: [“JavaScript”, “Function Parameters”, “ES6”, “ES2015”, “ES2018”, “Default Values”, “Trailing Commas”, “Spread Operator”, “Destructuring”]