Last Updated: February 25, 2016
·
732
· mejarc

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;

    ...

}

1 Response
Add your 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 ·