Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a default parameter value for a JavaScript function

I would like a JavaScript function to have optional arguments which I set a default on, which get used if the value isn't defined (and ignored if the value is passed). In Ruby you can do it like this:

def read_file(file, delete_after = false)   # code end 

Does this work in JavaScript?

function read_file(file, delete_after = false) {   // Code } 
like image 210
Tilendor Avatar asked May 21 '09 20:05

Tilendor


People also ask

How do you define a default value for a JavaScript function parameter?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined .

What is the default return value of a function in JavaScript?

A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined .

Can we use default parameter to first parameter in JavaScript?

You still need to provide the first parameter regardless of its default value.


2 Answers

From ES6/ES2015, default parameters are in the language specification.

function read_file(file, delete_after = false) {   // Code } 

just works.

Reference: Default Parameters - MDN

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

You can also simulate default named parameters via destructuring:

// the `= {}` below lets you call the function without any parameters function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)     // Use the variables `start`, `end` and `step` here     ··· } 

Pre ES2015,

There are a lot of ways, but this is my preferred method — it lets you pass in anything you want, including false or null. (typeof null == "object")

function foo(a, b) {   a = typeof a !== 'undefined' ? a : 42;   b = typeof b !== 'undefined' ? b : 'default_b';   ... } 
like image 148
Tom Ritter Avatar answered Oct 03 '22 00:10

Tom Ritter


function read_file(file, delete_after) {     delete_after = delete_after || "my default here";     //rest of code } 

This assigns to delete_after the value of delete_after if it is not a falsey value otherwise it assigns the string "my default here". For more detail, check out Doug Crockford's survey of the language and check out the section on Operators.

This approach does not work if you want to pass in a falsey value i.e. false, null, undefined, 0 or "". If you require falsey values to be passed in you would need to use the method in Tom Ritter's answer.

When dealing with a number of parameters to a function, it is often useful to allow the consumer to pass the parameter arguments in an object and then merge these values with an object that contains the default values for the function

function read_file(values) {     values = merge({          delete_after : "my default here"     }, values || {});      // rest of code }  // simple implementation based on $.extend() from jQuery function merge() {     var obj, name, copy,         target = arguments[0] || {},         i = 1,         length = arguments.length;      for (; i < length; i++) {         if ((obj = arguments[i]) != null) {             for (name in obj) {                 copy = obj[name];                  if (target === copy) {                     continue;                 }                 else if (copy !== undefined) {                     target[name] = copy;                 }             }         }     }      return target; }; 

to use

// will use the default delete_after value read_file({ file: "my file" });   // will override default delete_after value read_file({ file: "my file", delete_after: "my value" });  
like image 41
Russ Cam Avatar answered Oct 03 '22 00:10

Russ Cam