Search code examples
javascripttypescript

Default value getting overriden by destructured array in function parameter


I am trying to understand the basics of typescript and javascript and have following code

function b (val = false, arr1, arr2)  {
  console.log('val is:',val); //has 1
  console.log('array val 1:',arr1); //has 2
  console.log('array val 2:',arr2); //has undefined
}
const a = () => {
  const ba = [1,2];
  b(...ba);
}
a();

val is getting value 1 instead of false. This behavior is same even if I define a typescript datataype like function b (val:boolean = false, arr1, arr2). Should the value of val not be false? What I was thinking would happen was arr1 and arr2 will get values 1 and 2 respectively and val will get false as it has a default value.


Solution

  • You can't just omit the first parameter. You should pass undefined for the parameter that you want to default:

    b(undefined, ...ba)
    

    Also, note that there's no destructured array, what you're using is "spread" syntax in your function call.

    If you want your parameters to also be an array you can:

    function b (val = false, ...arr)  {
      console.log('val is:',val); //has false
      console.log('array val 1:',arr[0]); //has 1
      console.log('array val 2:',arr[1]); //has 2
    }
    b(undefined, ...[1,2]);