h33
h33

Reputation: 1344

Function declarations and how they create variables in the current scope

I was reading this article about js functions. https://dmitripavlutin.com/6-ways-to-declare-javascript-functions/

and it says "The function declaration creates a variable in the current scope with the identifier equal to function name. This variable holds the function object."

So I did some experiments to learn more.

function a () {
    return 1;
}
console.log(typeof a === "function")
console.log(typeof a === "number")

This outputs
True
False

Which isn't surprising, then when I run this.

var a = 1;
function a () {
    return 1;
}
console.log(typeof a === "function")
console.log(typeof a === "number")

The output is
False
True

So although a is allocated to a number and then later allocated to a function, it ends up being a number in the end.

Is there some kind of rule that says variable declarations override function declarations or is there more to it?

Upvotes: 0

Views: 37

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

Function declarations are hoisted to the top of their containing function (or the outermost block). Your lower code is equivalent to the following:

var a = function a () {
    return 1;
}
// next line reassigns `a` to number:
a = 1;
console.log(typeof a === "function")
console.log(typeof a === "number")

If you log a before the line a = 1, you'll see that it is indeed a function before it gets reassigned:

console.log(typeof a);
var a = 1;
console.log(typeof a);
function a () {
    return 1;
}

Upvotes: 2

Related Questions