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
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#