How to set default values for function parameters in JavaScript?

June 8, 2021 - 3 min read

To set default values for function parameters in JavaScript, you can use the assignment (=) operator on the parameter variables and then set the default value there.

TL;DR

// Function which greets a person
// with default value as "anonymous user"
// for name parameter
function greetPerson(name = "anonymous user") {
  console.log(`Hello ${name}`);
}

// call the function but with no value
greetPerson(); // "Hello anonymous user"

Let's say we have a function called greetPerson which will accept a person's name as an argument and upon calling the function greets the person by calling their name. Eg: "Hello John".

So the function will look like this,

// Function which greets a person
function greetPerson(name) {
  console.log(`Hello ${name}`);
}

Now if we call the function we by passing John as an argument to the greetPerson function we would see Hello John in the console. It can be done like this,

// Function which greets a person
function greetPerson(name) {
  console.log(`Hello ${name}`);
}

// call the function
greetPerson("John"); // "Hello John"

Till now we are fine.

But what if we didn't pass any value as an argument to the function and simply call the function like this,

// Function which greets a person
function greetPerson(name) {
  console.log(`Hello ${name}`);
}

// call the function but with no value
greetPerson(); // "Hello undefined"

We see the output as Hello undefined, which would be a bad practice and a bad experience for the user.

One of the ways to solve this problem would be to assign a default value to the name parameter or variable in the greetPerson function. Let's set the default value as anonymous user.

  • To set the default value we can use the assignment operator (=) on the function parameter, in our case it is the name parameter.

It can be done like this,

// Function which greets a person
// with default value as "anonymous user" for name parameter
function greetPerson(name = "anonymous user") {
  console.log(`Hello ${name}`);
}

Now if we call the function without the value, we can see the value as Hello anonymous user. It can done like this,

// Function which greets a person
// with default value as "anonymous user" for name parameter
function greetPerson(name = "anonymous user") {
  console.log(`Hello ${name}`);
}

// call the function but with no value
greetPerson(); // "Hello anonymous user"

And we have successfully set the default value for the name parameter in the greetPerson function.

That's all! 😃

See the above code live in JSBin

Feel free to share if you found this useful 😃.