I want to write a function that takes an optional argument and changes its behavior depending on whether or not that argument is provided. This is the first way I thought to do this:
function foo(optionalArg) {
if (optionalArg) {
// do something with the optionalArg
} else {
// do something different
}
}
Is this the best way to do this, or is there a safer/better way?
EDIT: If you actually read the question, you'll notice that it's different than the "duplicates" some claim this is. I know how to provide default values to a function's arguments; I found those links when I was trying to figure this out on my own first. But I'm not looking for how to do that. I'm looking for the best way to change my function's behavior based on whether or not the argument was provided.
Answer
The way you are doing is it fine, but here's a few tips.
1) In ES6 you could have a default argument in case one is not supplied:
function foo(optionalArg = 'something cool') {
// have your function go about its business as usual
}
2) Same as above, except not using ES6:
function foo(optionalArg) {
if (optionalArg === undefined) {
optionalArg = 'something cool'
}
// have your function go about its business as usual
}
3) Check your argument against undefined to avoid false positives:
function foo(optionalArg) {
if (optionalArg !== undefined) {
// do something with the optionalArg
} else {
// do something different
}
}
4) Place the longer block in the else statement for optimal readability:
function foo(optionalArg) {
if (optionalArg !== undefined) {
// do something with the optionalArg
} else {
// do something different
// big
// huge
// grandiose
// epic
}
}
I hope that helps!
No comments:
Post a Comment