Optional function arguments for JavaScript
In Ruby, there's this:
def foo(bar, options={})
...
end
Or even:
def foo(bar, baz=1)
...
end
In JavaScript, there's...uh...something less memorable. That's why I'm storing this snippet here.
foo = required parameter
baz = optional parameter
function foo(bar, baz){
baz = (typeof baz === "undefined") ? "defaultValue" : baz;
...
}
Written by Melanie Archer
Related protips
1 Response
Using an object as argument allows more arbitrary/optional combinations/order of arguments.
But it requires more documentation (which is good!)
function foo(params){
params = params || {};
params.bar = params.bar || "something";
params.baz = params.baz || "defaultValue";
}
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#