Skip to content

JavaScript Function Parameters

Default Parameters

By default, parameters are set to undefined

js
function add(a, b) {
 return a + b;
}
add(1) // 1 + undefined

A default can be set for each argument in the parameter.

js
function add(a = 0, b = 0) {
	return a + b;
}
add(1) // 1 + 0

Adding defaults to the parameters reduce errors and can make the functions more concise.

js
function getData(url, callback = () => {}) {
	fetch(url).then((res) => {
		return res.json();
	}).then((data) => {
		callback(data);
	});
}

// No callback, no error
getData('https://api.example.com');

// With callback.
getData('https://api.example.com', console.log) // output: data

Named Parameters

Using object literals and destructuring we can create functions that are easier to understand than positional parameters.

js
// positional parameters
function getFullName(firstName, lastName) {
	return `${firstName} ${lastName}`;
}

// not clear what the parameters represent
getFullName('Bob', 'Jon');

// named parameters
function getFullName({firstName = '', lastName = '' }) {
	return `${firstName} ${lastName}`;
}

// more verbose but clearer intent
getFullName({firstName: 'Bob', lastName: 'Jon'})

It's also easier to have optional parameters as the number of parameters grows:

js
function getFullName(firstName='', middleName='', lastName='') {
	return `${firstName} ${middleName} ${lastName}`;
}
// parameters have to be in order
getFullName('Bob', '', 'Jon') 

vs

function getFullName({firstName='', middleName='', lastName=''}) {
	return `${firstName} ${middleName} ${lastName}`;
}
// middleName can be optional
getFullName({firstName: 'Bob', lastName: 'Jon'})

Rest Parameters

Using rest parameters, we can create functions that takes indefinite numbers of parameters.

js
function sum(...numbers) {
	return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15