1. Computing & Technology

JavaScript By Example

Using Functions: 9. Optional Arguments

From , former About.com Guide

You don't need to make use of the argument list in order to be able to make arguments optional in JavaScript. When fewer parameters are passed to a function than the function has arguments defined then the excess arguments will be undefined. It is therefore just a simple matter of testing for undefined arguments where you want them to be optional.

In this example we create an add function that will add two or optionally three numbers together.


add = function(a, b, c) {
var tot = a + b;
if (c !== undefined) tot += c;
return tot;
}

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example

©2012 About.com. All rights reserved.

A part of The New York Times Company.