A complete guide on – JavaScript Default Parameters

JavaScript Tips

Introduction

In JavaScript, function parameters default to undefined. In each programming language has one or the other specified default values for the in-built functions and properties. The same applies to JavaScript also where it enables the function to own their default values.

JavaScript has become the main base for several reasons and it is being utilized desperately in the most popular frameworks such as Angular, react, and Vue. In this blog, we will put rays on JavaScript default parameters.

What is the difference between arguments and parameters?

  • Before making a move on the default parameters, it is crucial to understand about arguments and parameters as many people get confuse about these two terms.
  • The parameters and arguments are two distinct aspects in a function.
  • Function parameters are the values that are passed within the definition of the function.
  • Function arguments are the real values that are passed within the function.

In the following code, you’ll create a function that returns the square of a given number, defined as x:

function square(x) {

  return x * x

}

square(5);                          

  • In this example, the x variable is a parameter, a named variable that passes to a function.
  • This will give output as 25.
  • In this case, 5 is an argument- a value passed to a function when it is invoked.
  • Often the value will be contained in a variable as well, like this given example.

const no = 5;

square(no);

  • This will also give same output i.e., 25.

What is the Default parameter in JavaScript?

  • The default parameter is a mechanism to set default values for function parameters, a value isn’t any passed in it i.e., it’s undefined.

Default Parameter Data Types

  • Any primitive value or object is used as a default parameter value.
  • In this topic, you may see how default parameters can be used with increased flexibility.
  • First, we set parameters using a string, number, boolean, object, array, and null value as a default value.
  • The following example is based on arrow function syntax in the default parameter.

const defaultNumber = (number = 42) => console.log(number)

defaultNumber()

const defaultString = (string = ‘ABC’) => console.log(string)

defaultString()

const defaultBoolean = (boolean = true) => console.log(boolean)

defaultBoolean()

const defaultObject = (object = { id: 4 }) => console.log(object)

defaultObject()

const defaultArray = (array = [1, 2, 3]) => console.log(array)

defaultArray()

const defaultNull = (nullValue = null) => console.log(nullValue)

defaultNull()

This will give the output as follows:

42

ABC

true

{id:4}

[1,2,3]

Null

  • Note down that any object created in a very default parameter will be created every time the function is called. This is one of the most common use cases for the default parameters is to use this actions to get values out of an object.
  • And another is, if you try to access a value from an object which it doesn’t exist, it will throw an error.
  • However, if the default parameter is an empty object, it will give you undefined values instead of throwing an error:

function settings(options = {}) {

  const { theme, debug } = options

}

  • First of all, define a settings function with a default object.
  • So, this will avoid the error caused by destructing objects that don’t exist.

What are Default function parameters in JavaScript?

  • Default function parameters grant named parameters to be begin with default values if no value or undefined is passed.

Syntax:

Function

[name]

([para1[ =defaultval1 ][, … ,paraN[ =defaultValN ]]])

{

statements

}

Example of Default function parameter

function multiply(a, b = 1) {

  return a * b;

}

console.log(multiply(6, 2));

console.log(multiply(6));

[output: 12, 6]

In the above example, the first called multiply function in that value of a is 6 and value of b is 2, and at that time, value should be printed within the console. And therefore, the output is 12. In the second, the value of a is 6, and therefore, the value of b is 1 which is acquired in the function that’s b=1. So the second output is 6 by multiplying the value of a and b.

A default parameter can also be a function definition

Let’s see the example of that:

function outer(

  parameter = function inner() {

    return 10

  }

) {

  return parameter()

}

outer()

  • This will give the output 10.
  • In the above example defines a parameter because the inner function and returns the call of the parameter.
  • The inner function is created from scratch whenever the outer function is invoked.

Using Expressions as Default Values

It’s also possible to produce expressions as default values.

Passing Parameters as Default Values

function sum(a= 2,  b = a,  c = a + b) {

    console.log( a + b + c );

}

sum();

In the above example,

The default value of x is 2.

The default value of y is ready to the x parameter.

The default value of z is that the sum of x and y.

If you reference the parameter that has not been initialized yet, You’ll get an error.

Let’s see the example for that,

function sum( a = b, b = 1 ) {

    console.log( a + b);

}

sum(); 

[ReferenceError: Cannot access ‘b’ before intialization]

Passing Function Value as Default Value

const sum = () => 15;

const calculate = function( a, b = a * sum() ) {

    return a + b;

}

const result = calculate(10);

console.log(result);           

[output: 160]

In the above example,

10 is passed to the calculate() function.

The value of x becomes 10.

The value of y becomes 150 because the sum function returns 15.

So the result is 160.

Passing undefined value

In JavaScript, when you pass undefined to a default parameter, the function takes the default value.

Let’s see an example,

function demo(x = 1) {

    console.log(x);

  }

demo(undefined); 

[output: 1]

When we pass the undefined it takes the default value is 1.

So the output will be 1.

Multiple default parameters

  • You can use as many default parameters as you wish within the function.
  • Let’s see the example of multiple default parameters.

function sum(a = 2, b = 3) {

  return a + b

}

sum()

  • First of all, we declare a sum() function with multiple default parameters.
  • This will give the output 5.
  • In further, the value utilized in a parameter can be used in any subsequent default parameter, from left to right.

Let’s see the example:

function createUser(name, rank, userObj = { name, rank }) {

  return userObj

}

const user = createUser(‘Abcd Efgh’, ‘demo’)

  • If you call the user here, you will get the following.
  • This will give the output as follows:

            {name:” Abcd Efgh ”, rank:” demo ”}

  • It is usually advanced to place all default parameters at the end of a list of parameters so that you can easily break off optional values.

Conclusion

In this blog, you learned what default parameters are and the way to use them. Now you’ll use default parameters and functions and easy to learn them. Another is you can also empty values or parameters to reduce the complexity of code.

Leave a Reply

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