Reputation: 411
I stumbled upon a function that looked like this:
function pivot(arr, start = 0, end = arr.length){
...some code
}
Is this the same as writing:
function pivot(arr){
let start = 0;
let end = arr.length;
...some code
}
If so, are there any particular use cases in which declaring variables in the parameter of a function is advantageous other than for the sake of brevity?
Upvotes: 0
Views: 29
Reputation: 5205
What you're seeing in this case is the Default Parameter. Here you can pass any values against these params, say start
as 5 and end
as 15. If you don't specify any values, the default values will be considered, i.e start as 0 and end as the length of arr
function pivot(arr, start = 0, end = arr.length){
...some code
}
On the other hand What you're seeing below is one variable declared (start
) and another value (end
) getting extracted from the parameter arr
:
function pivot(arr){
let start = 0;
let end = arr.length;
...some code
}
Upvotes: 1
Reputation: 1200
What you're seeing in the function signature is parameters that have a default value. This allows you to pass some or all of the parameters at your discretion, while ensuring there is a usable value for each variable.
Upvotes: 1