navedhn
navedhn

Reputation: 3

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

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);

Upvotes: 0

Views: 37

Answers (2)

pope_maverick
pope_maverick

Reputation: 980

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 :()"
}

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371233

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));

Upvotes: 2

Related Questions