1

In javascript, what's the purpose of assigning variable to function declaration?

var test = function(){console.log("Hello world")} 

over

function test(){ console.log("Hello world")

Also, I don't understand the code below does not work. Is it because hoisting does not care about variable assignment? (cares only about variable declaration)

vartest();
var vartest = function(){
  console.log("Hello var function")
}
  • There's hardly ever a good reason to use the variable declaration that is initialised with a function expression over a function declaration. Only because it's possible doesn't mean it's useful. – Bergi Feb 13 '16 at 20:53
  • Yes, exactly, only the declaration `var vartest;` is hoisted, the assignment happens after you tried to call the function. – Bergi Feb 13 '16 at 20:54

1 Answers1

0

The first part is not answerable. There's no "single purpose" and there are varied use cases for this.

The second part is simpler. Hoisting can be described as "pulling up declarations". This means that variables and functions are effectively always declared at the top of their scope. That does not mean they are assigned values at the top. Values are assigned at the original location of the "pre-hoisting" declaration. However, since named functions are not assigned a value, the hoisting effectively moves the declaration and implementation as a whole to the top of the scope.

This does not happen for functions assigned to variables, and hence the code "does not work".

Amit
  • 45,440
  • 9
  • 78
  • 110