Last Updated: February 25, 2016
·
930
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
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