Default parameters make working with functions a whole lot easier. Using default parameters, you can tell your functions what parameters they should use in the case that you haven’t specified any. This can help avoid errors and makes your code more readable.
JavaScript introduced default parameters in ES2015. These allow you to initialize a function with predefined values.
In this guide, we’re going to talk about what default parameters are, how you can use them, and what types of expressions you can specify as a default parameter. We’ll walk through a few examples so that you’ll have all the code you need to get started.
Parameters vs. Arguments: The Battle
Before we begin, let’s address an age-old question from beginners: what is the difference between a parameter and an argument? You need to know the difference before you start working with default parameters in JavaScript.
A parameter is a named variable that you pass into a JavaScript function. A parameter never has a direct value assigned to it. It is a placeholder for a value you are going to pass into a function. Here’s an example of a parameter:
function sayHello(name) { console.log("Hello, " + name); }
In this example, “name” is our parameter. It doesn’t have any value assigned to it.
Arguments, on the other hand, are values that are passed to a function:
sayHello("Brett");
Our code returns: “Hello, Brett”. “Brett” is an example of an argument, which was the value we passed through our function.
Calling a function without specifying all of its parameters can lead to an error:
sayHello()
Our code returns: Hello, undefined
. That’s because we haven’t passed a value to our function.
JavaScript Default Parameters
We can overcome this problem by specifying a default parameter. A default parameter allows you to specify a value that will be assigned to a parameter in the case that none is specified.
Default value assignment uses the assignment operator:
function sayHello(name="World") { console.log("Hello, " + name); } sayHello();
Our code returns: Hello, World
. You can see that we’ve not specified an argument in this example. Instead, we’ve set a default function parameter. In this case, any time an argument is not specified, the value of the “name” parameter in our function becomes “World”.
This is much easier than having to check manually for whether a value is specified.
A default parameter can have any primitive value or object assigned as its value. Here are a few examples of valid default parameters:
- String: “Latte”
- Number: 2.40
- Boolean: true
- Array: [“Steven”, false]
- Object: {name: “Steven”, loyaltyCustomer: false }
Specifying Multiple Default Parameters
There’s no limit on how many default params you can specify in a function. Consider the following code:
function createOrder(coffee="Espresso", price=1.75) { console.log("Order: " + coffee); console.log("Price: $" + price); } createOrder();
Our code returns:
Order: Espresso Price: $1.75
In this example, we’ve specified two default parameters: coffee and price. You can also mix up the parameters you specify between default and regular parameters. When you do this, you’ve got to place any regular parameters before default parameters. Consider this example:
function createOrder(coffee, price=1.75) { console.log("Order: " + coffee); console.log("Price: $" + price); } createOrder("Cappuccino");
Our code returns:
Order: Cappuccino Price: $1.75
We’ve specified one argument: Cappuccino. This is the name of the coffee that we have ordered. Because we haven’t specified a default value for this parameter, we need to specify an argument value; otherwise, “undefined” would be returned.
We declared that the default value for “price” should be “1.75”. Because we set this default parameter, any time we don’t specify a price it will be automatically set to “1.75”.
It’s important that you specify any regular parameters before your default parameters. This is because the values for regular parameters are assigned in order of when they appear in your function call.
Functions as a Default Parameter
A function can be set as a default parameter. This is useful if the value you want to pass into a function is calculated using another function.
In the following code snippet, we’re going to create a function that generates a pseudo-random username for a new player on a video game:
function getRandomUsername() { var number = Math.floor(Math.random() * 100); var username_list = ['Crash', 'Steve', 'Lucinda', 'Ellie']; var username = username_list[Math.floor(Math.random() * username_list.length)]; var final_username = username + number; return final_username; } function createUser(username = getRandomUsername(), email) { console.log('Your username is: ' + username); console.log('Your email is: ' + email); } createUser('test@test.com');
Our code returns:
Your username is: Crash87 Your email is: test@test.com
Let’s break down our code.
We have declared a function called getRandomUsername()
which generates a pseudo-random username. This works by generating a random number and selecting, at random, one username from a list of four usernames. The random number is then added to the end of the username. This function returns the newly-generated username
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
In our createUser
function, we’ve set the default value of the “username” parameter to be equal to our getRandomUsername()
function. This means that whenever we don’t specify a username for our new user, a random one is generated.
Our code then prints out the user’s username as well as their email address to the console.
Conclusion
Default parameters allow you to set a value that will be assigned to a parameter if one is not specified as an argument in a function call. Default parameters help make your functions easier to read and reduce issues that may arise when a value is not passed to a function.
Now you’re ready to start working with JavaScript default parameters like an expert!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.