Passing an Optional Variable to a JavaScript Function

October 13th, 2010 - Posted by Steve Marks to Javascript / jQuery, Web Development.

Ever needed to call a function expecting parameters but use the functions default value rather than passing the same value each time? Let me give you an example:

function do_something(my_var) {
	alert(my_var);
}
do_something();

In doing the above you will get ‘undefined’ output. So how do we assign the ‘my_var’ to a value if it’s not supplied?

The Solution

function do_something(my_var) {
	my_var = my_var || 'You did it!';
	alert(my_var);
}
do_something();

All we’re doing here is checking if the variable is undefined or not. If it’s been supplied as a parameter then use it, else assign it to a default value.

This entry was posted on Wednesday, October 13th, 2010 at 7:55 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first