0

I have a function with an optional parameter. I'm defaulting the value to 1000 if the parameter isn't supplied like so:

function zoom( coords, zoomSpeed){
  zoomSpeed = zoomSpeed || 1000;
  //rest of code
}

This works for testing presence of the parameter, but I also want to make sure a number was supplied as the parameter. I'm using the following but it seems like there is a better way to do this.

function zoom( coords, zoomSpeed){
  if (typeof zoomSpeed === "number"){
    zoomSpeed = zoomSpeed;
  }else{
    zoomSpeed = 1000;
  }
  //rest of code
}

Any feedback on a better way to do this would be appreciated.

user3226861
  • 181
  • 1
  • 4
  • 14

3 Answers3

4

This is shorter:

if (typeof zoomSpeed !== "number"){
    zoomSpeed = 1000;
}
Simon H
  • 20,332
  • 14
  • 71
  • 128
2

... or

zoomSpeed = parseInt(zoomSpeed) || 1000

marekful
  • 14,986
  • 6
  • 37
  • 59
0

You can use your zoom(..., "5") through following code

function zoom( coords, zoomSpeed){
  zoomSpeed = Number(zoomSpeed) !== NaN ? Number(zoomSpeed): 1000;
  //... 
}
Sherali Turdiyev
  • 1,745
  • 16
  • 29