Saturday, March 10, 2012

Optional Parameter in Javascript

Javascript does not officially allows you to declare optional parameter but there is still a way you can handle them. Here we go!


function generateForm(id)
{

    var editable = false;

    if (arguments.length == 1 && typeof id!= "undefined")

    {

        editable = true;

    }

    if(!editable)

    {

        alert("add form");

    }

    else

    {

        alert("edit form");

    }

}

As you can see, what all I did that I checked the length of given arguments and then also checked whether there is undefined type, there would be an undefined type if you provide no parameter. By simply checking this you can implement optional parameters