JavaScript default arguments like in Ruby

In Ruby we can assign a default value to the input parameters of a function in case we call the function without arguments (Rubyists always call a function a method):

# Ruby lang:
def add2(num=0)
puts num + 2

When we call the above function with an argument of 3 we get a result of 5.


If however we call add2() without arguments we will get the value 2 because 0 + 2 = 2. The reason for the default argument value is to avoid getting an error from Ruby.

In JavaScript we don’t have such thing as default parameters in functions ( that will change in ECMAScript 6). If we call a function without values for its parameters we will not get an error. However, things just may not work as desired.

We can emulate the idea used by Ruby in the following manner:

// JavaScript:
function add2 (num){
   if(typeof(num)=== "undefined") num = 0;
   return num + 2;

So if we call the function with an argument of 3 it returns 5. If we call the function with no argument it will return 2 which is the sum of 0 + 2.

Side note: There is a library on the works that provides support for optional and default function parameters in JavaScript: Args.js


Author: tarau

technical writer, web technologies

One thought on “JavaScript default arguments like in Ruby”

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s