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
}
Use this if you want to use latest
ECMA6
syntax:It is called
default function parameters
. It allows formal parameters to be initialized with default values if no value or undefined is passed. NOTE: It wont work with Internet Explorer or older browsers.For maximum possible compatibility use this:
Both functions have exact same behavior as each of these example rely on the fact that the parameter variable will be
undefined
if no parameter value was passed when calling that function.Here foo() is a function which has a parameter named argValue. If we don’t pass anything in the function call here, then the function throwIfNoValue() will be called and the returned result will be assigned to the only argument argValue. This is how a function call can be used as a default parameter. Which makes the code more simplified and readable.
This example has been taken from here
Yes, This will work in Javascript. You can also do that: