How to Use Optional Parameters in Functions in Javascript

Sometimes you would want to have an optional parameter with a default value when you call a function. How do you do that? It’s quite simple. Javascript does not validate whether the parameters that are declared on the function are actually passed to the function when you call it. Thus, you can call a function omitting the parameters that are optional; however, you would have to assign the default values since it’s not possible to do that when you declare a function, like you would be able to do in PHP or C#, and you would have to do so in the function itself.

function tellGrassColor(grassColor)
{
	if (typeof grassColor == 'undefined') { grassColor = 'green'; }
	alert(grassColor);
}

tellGrassColor('red');
tellGrassColor();

The

typeof grassColor

will return ‘undefined’ if the parameter is not passed to the function and we will then set grassColor variable to the default value.
Try it yourself!

This entry was posted in Javascript and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *