It is possible to use default parameter value its same function name

31 Views Asked by At

I would like to know if it is possible to use the function itself in its default parameter.

function somename(a,b=somename()){
    return a+b;
}
somename(10);
2

There are 2 best solutions below

0
CertainPerformance On BEST ANSWER

Sure you can, as long as you design the logic such that it doesn't enter an endless recursive loop. For example:

function somename(a, b = somename(3, 5)) {
  return a + b;
}
console.log(somename(10));

1
pope_maverick On

Yes you can.

Functions are hoisted along with it's body. So the params and the inner useages are considered as it's environment, not the function itself. Unless you accidently invoke with the function calling signature "()"

eg: someName() // invoking the function someName
    someName // will search for the variable definition along the scope chain.

so, if you accidently invoke that function inside, you'll end up with a recursively calling infinite loop, unless there is a condition to return from it

eg:
function someName(a = someName) {
 someName(); // Now you are invoking the function with the signature :()"
}