Parameters and Arguments

Function Parameters and Defaults

Todd Motto by Todd Motto Google Developer Expert Icon Google Developer Expert
JavaScript Icon

Learn JavaScript the right way

Premium JavaScript courses to skyrocket your skills to the top.

5x Courses: Basics, Masterclass, HTML5 APIs, DOM, Testing with Jest.

Functions become useful when they are dynamic.

Dynamic means we can pass different data into a function, to transform or perform operations on it to achieve a different result.

This is where we introduce a “function parameter”.

A parameter is a variable scoped to that function that expects a dynamic value, for example the name of a drink:

function drink(name) {}

The function can then be called multiple times, supplying different data.

Data passed into functions is known as an “argument”, it’s important to clarify the different between a parameter and argument:

// name = parameter
function drink(name) {}

// data = arguments
drink('Lemonade');
drink('Water');

Parameters can then be accessed inside the function to perform operations:

function drink(name) {
  console.log(`Let's drink a ${name}`);
}

drink('Lemonade'); // Let's drink a Lemonade
drink('Water'); // Let's drink a Water

Functions that rely on parameters need to be safely considered. What if an argument is not supplied?

Enter the “default parameter”.

A traditional method to supply default parameters involves a safety check and reassignment of that parameter if it doesn’t exist:

function drink(name) {
  if (!name) {
    name = 'Coffee';
  }
  console.log(`Let's drink a ${name}`);
}

drink(); // Let's drink a Coffee
drink('Water'); // Let's drink a Water

This method would be preferred for also creating more complex default parameters.

For simpler defaults we can opt for a modern JavaScript feature known as the “default parameter”.

The default value is assigned to the parameter inside the function parenthesis:

function drink(name = 'Coffee') {
  console.log(`Let's drink a ${name}`);
}

drink(); // Let's drink a Coffee
drink('Water'); // Let's drink a Water

This approach creates a minimal code footprint while being clear and concise.

For more complex use cases, using the “traditional” approach would be required as the default parameter only supports basic types.

Functions can also contain any number of parameters, comma separated:

function drink(name = 'Coffee', size = 'medium') {
  console.log(`Let's drink a ${size} ${name}`);
}

drink('Water', 'large'); // Let's drink a large Water

Time to move on and look at accessing function parameters dynamically through JavaScript’s arguments object and another modern feature, the “rest parameter”.

Keywords or Variables

« Named and Anonymous Functions

Dynamic Arguments

Rest Parameters and Arguments »