user3562812
user3562812

Reputation: 1839

Javascript syntax on function

Can you refer to function as array in javascript? In the code below, function factorial is treated as an array..

function factorial(n) {
  if (isFinite(n) && n>0 && n==Math.round(n)) { 
    if (!(n in factorial))
      factorial[n] = n * factorial(n-1);
    return factorial[n];
  }
  else 
    return NaN;
}

factorial[1] = 1;

Upvotes: 1

Views: 46

Answers (2)

Ahmed
Ahmed

Reputation: 186

the functions can not be arrays, they could have properties .

function factorial(n){
    if(n == 1)
        return 1;

    return (n * factorial(n - 1) );
}

Upvotes: 0

Quentin
Quentin

Reputation: 944445

Functions are objects. They can have properties (and have a number by default).

You usually can't treat them as arrays (since they don't have Array on their prototype chain and are missing most of the methods that arrays have) but ['property name'] is a general way to access properties and is not array specific.

Upvotes: 5

Related Questions