View Full Version : Empty Function Parameters

01-27-2009, 11:59 PM
How do i declare a default value in a function? I have a simple function

function color_input(id,token){

if (!empty(token)){
document.getElementById(id).style.backgroundColor = '#2A2A2A';
document.getElementById(id).style.color = '#DDC58C';
document.getElementById(id).style.backgroundColor = '';
document.getElementById(id).style.color = '';


Called in HTML like

<input type="text" id="example_name" onblur="color_input('example_name');">

You will notice that the #2 parameter is missing in the html call. Sometimes i don't have it to send. in PHP i would just set the functions second param like token=''

function color_input(id,token=''){}

How do i set a default param in a JS function?

01-28-2009, 12:03 AM
Like so:

function color_input(id,token){
if( token == null )
token = defaultvalue;


On second thoughts, you could also do this:

token = token || defaultvalue

I think that could go wrong though if you for example tried to use 0. It's better to stick with the first example and use a type checking comparison with ===.

01-28-2009, 12:33 PM
@flynch01 - thanks much its perfect.