Search code examples
javascriptfactorial

What is the reason that the OR operator is in this function?


I read the following code but I can not understand what it means "||" in this context:

function factorial(numero) {
  numero = numero || 1
  return numero * factorial(numero - 1)
}

I understand the logical operators but I do not find the sense to call the function if you pass any argument. That is why the reason for my question.


Solution

  • That's called short-circuiting. || is the OR operator, but the way it is evaluated, it will look at the left side (and never look at the right side, thus "short-circuiting".

    If it is true, it will use that value. If it is false, it will use the right side. Here, if 'numero' is undefined, it will be false, and therefore the placeholder default value of 1 will be used.