Created
April 29, 2012 10:03
-
-
Save klovadis/2549131 to your computer and use it in GitHub Desktop.
How to use optional arguments in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// example function where arguments 2 and 3 are optional | |
function example( err, optionalA, optionalB, callback ) { | |
// retrieve arguments as array | |
var args = []; | |
for (var i = 0; i < arguments.length; i++) { | |
args.push(arguments[i]); | |
} | |
// first argument is the error object | |
// shift() removes the first item from the | |
// array and returns it | |
err = args.shift(); | |
// last argument is the callback function. | |
// pop() removes the last item in the array | |
// and returns it | |
callback = args.pop(); | |
// if args still holds items, these are | |
// your optional items which you could | |
// retrieve one by one like this: | |
if (args.length > 0) optionalA = args.shift(); else optionalA = null; | |
if (args.length > 0) optionalB = args.shift(); else optionalB = null; | |
// continue as usual: check for errors | |
if (err) return callback(err); | |
// for tutorial purposes, log the optional parameters | |
console.log('optionalA:', optionalA); | |
console.log('optionalB:', optionalB); | |
/* do your thing */ | |
} // example() | |
// invoke example function with and without optional arguments | |
example(null, function (err) { /* do something */ }); | |
example(null, 'AA', function (err) {}); | |
example(null, 'AAAA', 'BBBB', function (err) {}); |
Cool. Thanks!
I get Error: SyntaxError: Unexpected string
where the arguments
is used. If i remove it, everything seems to work fine. Any help please? Thanks
thanks
Thank you @klovadis and @rossipedia !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@adrianblynch That's only the case if
optional_1
andoptional_2
are independent. If you structure your inputs tofunction
in such a way whereoptional_2
can be present only ifoptional_1
is present (even if that requires sendingfunction(required, null, optional_2, required)
, you don't have to worry about that.If the signature is
function(required, optional_1, optional_2)
whereoptional_1
andoptional_2
are independent of each other and you pass infunction(required, optional_2)
, unless you design your input to match specific unique criterion, you're right: there's no way to for the function know that you meanoptional_2
instead ofoptional_1
.Long Story Short: design your function to require
optional_1
in order to acceptoptional_2
.