Clue Mediator

Default Parameters in JavaScript

📅December 4, 2019
🗁JavaScript

Today we will give you examples of default parameters in JavaScript. We will show you the list of possible ways to handle the default parameters in JavaScript.

Default Parameters in JavaScript, Understanding Default Parameters in Javascript with examples, Set a default parameter value for a JavaScript function, es6 default parameters object, javascript multiple optional parameters, javascript default value if undefined, javascript function optional parameter default value.

Checkout more articles on JavaScript:

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments to the function, its parameters will have the default values of `undefined`.

Table of Contents: Default Parameters in JavaScript

  1. Using the logical OR (||) operator
  2. With additional type check (safer option)
  3. Expressions can also be used as default values

1. Using the logical OR (||) operator

In below example, we used OR (||) operator to assign default value in variable.

So let’s say if you will not pass the value of function parameters or pass it as `null` or `undefined` then by default it will assign the `0` & `10` to the variables.

function calculate(val1, val2) {
  var value1 = val1 || 0;
  var value2 = val2 || 10;

  return value1 + value2;
}
calculate(1, 3); // Output: 4
calculate(); // Output: 10
calculate(5); // Output: 15
calculate(null, 5); // Output: 5

2. With additional type check (safer option)

Here we used the conditional operator `(? :)`. It's also known as a ternary operator. It has a three operands.

Look at the below example, it will check the condition `(typeof number !== "undefined")` if it is true then return `parseInt(number)` otherwise return `0`.

If you are not sure about the value type of the variable then you can use ternary operator to reduce the bug in code.

function convertToBase(number, base) {
  number = (typeof number !== "undefined") ? parseInt(number) : 0;
  base = (typeof base !== "undefined") ? parseInt(base) : 10;

  return number.toString(base);
}

3. Expressions can also be used as default values

Any JavaScript expressions can also be used as default values for function parameters.

Here we used the 0 as default value in parameter and also you can use `getDefaultNumber()` function as default values in parameter of another function. So we don’t need to use the OR (||) operator to assign default value in variable.

function getDefaultNumber() {
  return 10;
}

function calculate(val1 = 0, val2 = getDefaultNumber()) {
  return val1 + val2;
}
calculate(1, 3); // Output: 4
calculate(); // Output: 10
calculate(5); // Output: 15
calculate(null, 5); // Output: 5

That’s it for today.

Thanks for reading and happy coding!