Sahand
Sahand

Reputation: 8360

Function declaration vs function expression causing different results

In this code snippet, trueFactorial(5) returns 120:

function factorial(num) {
  if (num <= 1) {
    return 1;
  } else {
    return num * arguments.callee(num - 1);
  }
}

var trueFactorial = factorial;

var factorial = function(num) {
  return 0;
}

console.log(trueFactorial(5));

But in this code snippet, trueFactorial(5) returns 0.

function factorial(num) {
  if (num <= 1) {
    return 1;
  } else {
    return num * arguments.callee(num - 1);
  }
}

var trueFactorial = factorial;

function factorial(num) {
  return 0;
}

console.log(trueFactorial(5));

The only difference is that we declared factorial through variable assignment in the first snippet. What is the reason for this difference?

Upvotes: 0

Views: 52

Answers (3)

Spitzbueb
Spitzbueb

Reputation: 5871

In the second example your function is hoisted and gets assigned to trueFactorial function. Meaning it is in the end a reference to the same function. In the first example the reference points to another address in memory.

See:

function factorial(num){
    if (num <=1){
        return 1;
    } else {
        return num*arguments.callee(num-1);
    }
}

var trueFactorial = factorial;

var factorial = function(num){
    return 0;
}

console.log(trueFactorial(5));//120

console.log(trueFactorial === factorial);//false

function factorial(num){
    if (num <=1){
        return 1;
    } else {
        return num*arguments.callee(num-1);
    }
}

var trueFactorial = factorial;

function factorial(num){
    return 0;
}

console.log(trueFactorial(5));//0

console.log(trueFactorial === factorial);//true

Upvotes: -1

ClementNerma
ClementNerma

Reputation: 1109

The JavaScript interpreter first looks at the declaration of all functions in your code with the function <...> (<arguments>) syntax. In your second snippet, you declare the function both time with this syntax, so the interpreter starts by seeing the first declaration, memorize its content, and then see another declaration. At this point, it will replace the first declaration by the new one.

When you use the var keyword, the declaration is not seen by the interpreter before the start, but while the code is running.

Upvotes: 0

Quentin
Quentin

Reputation: 943207

Function declarations are hoisted. Variable assignments are not.

In example one, you assign the first function to trueFactorial.

In example two, the second function is hoisted so it gets assigned to trueFactorial.

Upvotes: 2

Related Questions