Default Parameters in 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.

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.

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.

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.

That’s it for today.

Thanks for reading and happy coding!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *