Default Parameters

Understand the implementation of default parameters.

We'll cover the following

Default parameters

When we define a named function, we can give a default value to any of its parameters by using the syntax param \\ value. When we call a function that’s defined with default parameters, Elixir compares the number of arguments we’re passing with the number of required parameters for the function.

  • If we’re passing fewer arguments than the number of required parameters, then there’s no match.

    For example, in the func(p1, p2 \\ 2, p3 \\ 3, p4) function, we need two parameters because it contains two default parameters. Now, if we pass a single argument in a function call— for example, func(1)—it’ll show the error.

  • If the two numbers are equal, then the required parameters take the values of the passed arguments, and the other parameters take their default values.

    For example, if we pass two parameters, like. func(1,4), then it’ll give output as [1,2,3,4].

  • If the count of passed arguments is greater than the number of required parameters, Elixir uses the excess to override the default values of some or all parameters.

    For example, if we pass three parameters, like func(10,15,20) , then it’ll give output as [10,15,3,20].

Remember that parameters are matched left to right.

Run Example.func(5,6), Example.func(5,6,7), and Example.func(5,6) types of commands to execute the code below.

Get hands-on with 1200+ tech skills courses.