JavaScript Default Parameters

JavaScript default parameters allow you to define default values for function parameters. This means that if a parameter is not provided when the function is called, the default value will be used instead. This is a useful feature when writing complex functions with multiple parameters, as it makes it easier to read and understand the code.

Why should you use it?

  • It simplifies complex functions with multiple parameters.
  • It reduces the amount of code needed to write a function.
  • It makes code easier to read and understand.

Default Parameters

JavaScript default parameters allow function arguments to be initialized with default values if no value or undefined is passed. When a function is called with fewer arguments than there are parameters, the missing parameters get the value of their corresponding default parameters. Default parameters are declared at the end of the parameter list, after all required parameters.

Syntax

The syntax for declaring a default parameter is to add an equal sign (=) after the parameter name, followed by the default value.
index.js
function greet(name, greeting = 'Hello') {
  console.log(greeting + ', ' + name);
}

Example

In the example below, the function greet() has two parameters, name and greeting. The default value of the parameter greeting is "Hello".
index.js
function greet(name, greeting = 'Hello') {
  console.log(greeting + ', ' + name);
}

greet("John");
greet("John", "Hi");
If we call the greet() function with one argument, the value of the greeting parameter will be "Hello". greet("John"); // Hello, John If we call the greet() function with two arguments, the value of the greeting parameter will be the value of the second argument. greet("John", "Hi"); // Hi, John