I would like a JavaScript function to have optional arguments which I set a default on, which gets used if the value isn't defined. 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
}
that solution is work for me in js:
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
, andreduce
. For example, consider this line of code:parseInt has an optional second parameter
function parseInt(s, [
radix=10])
but map callsparseInt
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:
Running the above snippet illustrates the dangers lurking behind default argument values for unused parameters.
As per the syntax
you can define the default value of formal parameters. and also check undefined value by using typeof function.
If for some reason you are not on ES6 and are using
lodash
here is a concise way to default function parameters via_.defaultTo
method:Which will set the default if the current value is NaN, null, or undefined
Following code may work in this situation including ECMAScript 6 (ES6) as well as earlier versions.
as default value in languages works when the function's parameter value is skipped when calling, in JavaScript it is assigned to undefined. This approach doesn't look attractive programmatically but have backward compatibility.
Just use an explicit comparison with undefined.