Set a default parameter value for a JavaScript function
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.
In ES6, you can 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
···
}
// sample call using an object
myFor({ start: 3, end: 0 });
// also OK
myFor();
myFor({});
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';
...
}
Sets the default value of a parameter based on the value of another parameter
This is a pretty standard pattern:
def consecutive_generator(size=20, start=0, end=None):
if end is None:
end = size + start
Does Java support default parameter values?
No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).
For constructors, See Effective Java: Programming Language Guide's Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.
Default value in Go's method
No, the powers that be at Google chose not to support that.
https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ
Default value parameter in Groovy as middle argument
In groovy you can assign default values to method's arguments, making those arguments optional.
Usually the optional arguments are the trailing ones, and that makes sence from the POV of calling such methods.
You could also declare default values for the middle arguments, like you did. In this case you should be aware of which arguments will get the defaults and which will not.
Consider the extension of your example:
def testMethod(arg1, arg2 = "arg2", arg3) {
println arg1
println arg2
println arg3
}
testMethod 1, 3
println '-----------'
def testMethod1(arg1, arg2 = "arg2", arg3 = 'arg3') {
println arg1
println arg2
println arg3
}
testMethod1 1,2
It prints:
1
arg2
3
-----------
1
2
arg3
So, when calling both methods with 2 arguments, the testMethod
replaces the 2nd arg with default, whereas the testMethod1
defaults the 3rd arg.
Using Default Arguments in a Function
I would propose changing the function declaration as follows so you can do what you want:
function foo($blah, $x = null, $y = null) {
if (null === $x) {
$x = "some value";
}
if (null === $y) {
$y = "some other value";
}
code here!
}
This way, you can make a call like foo('blah', null, 'non-default y value');
and have it work as you want, where the second parameter $x
still gets its default value.
With this method, passing a null value means you want the default value for one parameter when you want to override the default value for a parameter that comes after it.
As stated in other answers,
default parameters only work as the last arguments to the function.
If you want to declare the default values in the function definition,
there is no way to omit one parameter and override one following it.
If I have a method that can accept varying numbers of parameters, and parameters of varying types, I often declare the function similar to the answer shown by Ryan P.
Here is another example (this doesn't answer your question, but is hopefully informative:
public function __construct($params = null)
{
if ($params instanceof SOMETHING) {
// single parameter, of object type SOMETHING
} elseif (is_string($params)) {
// single argument given as string
} elseif (is_array($params)) {
// params could be an array of properties like array('x' => 'x1', 'y' => 'y1')
} elseif (func_num_args() == 3) {
$args = func_get_args();
// 3 parameters passed
} elseif (func_num_args() == 5) {
$args = func_get_args();
// 5 parameters passed
} else {
throw new \InvalidArgumentException("Could not figure out parameters!");
}
}
Python: default value of function as a function argument
You can do the following:
def myF(a, b=None):
if b is None:
b = a - 1
return a * b - 2 * b
Related Topics
"X Does Not Name a Type" Error in C++
How Do Conversion Operators Work in C++
Throw Keyword in Function'S Signature
C++ Detect When User Presses Arrow Key
Linux: Executing Child Process With Piped Stdin/Stdout
C/C++ Unsigned Integer Overflow
Why Isn't There a Std::Shared_Ptr≪T[]≫ Specialisation
Std::Thread Pass by Reference Calls Copy Constructor
Overload Resolution Between Object, Rvalue Reference, Const Reference
Is Sizeof in C++ Evaluated At Compilation Time or Run Time
How to Write a Short Literal in C++
Does Const-Correctness Give the Compiler More Room For Optimization
Optional Parameters With C++ Macros