[javascript] Set a default parameter value for a JavaScript function

I would highly recommend extreme caution when using default parameter values in javascript. It often creates bugs when used in conjunction with higher order functions like forEach, map, and reduce. For example, consider this line of code:

['1', '2', '3'].map(parseInt); // [1, NaN, NaN]

parseInt has an optional second parameter function parseInt(s, [radix=10]) but map calls parseInt with three arguments: (element, index, and array).

I suggest you separate your required parameters form your optional/default valued arguments. If your function takes 1,2, or 3 required parameters for which no default value makes sense, make them positional parameters to the function, any optional parameters should follow as named attributes of a single object. If your function takes 4 or more, perhaps it makes more sense to supply all arguments via attributes of a single object parameter.

In your case I would suggest you write your deleteFile function like this: (edited per instead's comments)...

_x000D_
_x000D_
// unsafe_x000D_
function read_file(fileName, deleteAfter=false) {_x000D_
    if (deleteAfter) {_x000D_
        console.log(`Reading and then deleting ${fileName}`);_x000D_
    } else {_x000D_
        console.log(`Just reading ${fileName}`);_x000D_
    }_x000D_
}_x000D_
_x000D_
// better_x000D_
function readFile(fileName, options) {_x000D_
  const deleteAfter = !!(options && options.deleteAfter === true);_x000D_
  read_file(fileName, deleteAfter);_x000D_
}_x000D_
_x000D_
console.log('unsafe...');_x000D_
['log1.txt', 'log2.txt', 'log3.txt'].map(read_file);_x000D_
_x000D_
console.log('better...');_x000D_
['log1.txt', 'log2.txt', 'log3.txt'].map(readFile);
_x000D_
_x000D_
_x000D_

Running the above snippet illustrates the dangers lurking behind default argument values for unused parameters.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to parameters

Stored procedure with default parameters AngularJS ui router passing data between states without URL C#: HttpClient with POST parameters HTTP Request in Swift with POST method In Swift how to call method with parameters on GCD main thread? How to pass parameters to maven build using pom.xml? Default Values to Stored Procedure in Oracle How do you run a .exe with parameters using vba's shell()? How to set table name in dynamic SQL query? How to pass parameters or arguments into a gradle task

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python

Examples related to default-parameters

Using an attribute of the current class instance as a default value for method's parameter T-SQL - function with default parameters C default arguments "Least Astonishment" and the Mutable Default Argument Does Java support default parameter values? Set a default parameter value for a JavaScript function