Bail3y
Bail3y

Reputation: 51

Does a function's name act as a variable?

I have a question about this code below:

function myfunc () {
return 2 + 2;
}

console.log(myfunc);

Does anyone know why, when we log 'myfunc' to the console, we get the entire function itself back? Or in other words, is 'myfunc' acting as a variable that holds the function's contents, or is it just referencing that function?

Because if I go ahead & add this to the code...

myfunc = undefined; //or any other value like myfunc = 20;

...then since myfunc's value is changed, I can no longer use it to invoke the function. So what is 'myfunc' really?

Upvotes: 1

Views: 142

Answers (1)

Pointy
Pointy

Reputation: 413826

The answer is yes, a function declaration creates a symbol in the local function scope (or global scope if the declaration is in that context) that works exactly like a variable declared with var (though function declarations are hoisted above var declarations).

Now, a function expression like this:

var x = function helloWorld() { return "hello world"; };

does not create a local "helloWorld" symbol (except when it does). The value of a function expression is a reference to the created function, and that can be assigned to a variable just like any other value.

Upvotes: 2

Related Questions