1

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;

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So, does function factorial have 1 as its property? Property can be accessed by using "functionName.property", but "factorial.1" clearly violates the rule...Thanks for clarification in advance.
@user3562812 — Yes. If you use dot notation to access a property then the property name has to be an identifier. Identifiers cannot start with a number. Bracket notation allows access to a much wider range of property names.
0

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.