-1
vm.fetchData = ($index) => {

}

I want to make $index as optional parameter.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Karan
  • 21
  • 1
  • 6
  • 1
    Don't pass the parameter when you call the function? – Heretic Monkey Jul 08 '21 at 16:32
  • If this is just vanilla JS, then you don't have a concept of a function signature that automatically enforces input-- if a function is invoked without parameters passed, the function will execute until it completes or it encounters an error (likely as a result of the missing parameter)-- there is no runtime check in which it will automatically error out from parameters being omitted that it was somehow "expecting". – Alexander Nied Jul 08 '21 at 16:37
  • 1
    Since AngularJS is using vanilla JS: Does this answer your question? [In JavaScript, how can I create a function with an optional parameter?](https://stackoverflow.com/questions/2225877/in-javascript-how-can-i-create-a-function-with-an-optional-parameter) – hc_dev Jul 08 '21 at 18:01

1 Answers1

0

Since you don't explicitly can declare parameters as optional in vanilla JS, you could simply ignore them in the function body:

vm.fetchData = function($index) {
    if(typeof $index == 'undefined') {
      // following should happen if parameter is missing
    } else {
      // following requires a parameter
    }
    
    // do the rest and return 
}

See also:

hc_dev
  • 8,389
  • 1
  • 26
  • 38