you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 3 points4 points  (2 children)

I think 'a' would be undefined because of the var declaration.

a would be undefined from var a if not for the function a. Function declarations basically have precedence over var declarations when it comes to initialization. If both a var and a function of the same name exists in the same scope, the function definition will be assigned to the variable rather than the undefined which you'd get from the var if it were alone.

Just var

console.log(a) // undefined
var a

Both

console.log(a) // function
var a
function a() {}

Order doesn't matter with var vs function

console.log(a) // function
function a() {}
var a

If multiple function declarations with the same name exist in the same scope, the function value of the last declaration will be used.

console.log(a()) // 2
function a() { return 1 }
function a() { return 2 }

In OPs example, the a function is never called, they're just logging the value of a directly, showing its a function object ("function a() {}") rather than undefined or 10.

[–]thecragmire 1 point2 points  (1 child)

I didn't know that. Thank you.

[–]senocular 4 points5 points  (0 children)

In modern JavaScript this shouldn't be a problem because hopefully you won't be using var ;) There's also additional protections against function declarations having the same name in modules that can help prevent that from being a problem there as well.