0

Here is the code

foo()    //first function call

function foo(){
    console.log("foo 1")
}

var foo=function(){
    console.log("foo 2")
}

function foo(){
    console.log("foo 3")
}

foo()    //second function call

the output for this code is this

foo 3
foo 2

if i comment the first function call then only foo 2 is printed and when i comment the last function call foo 3 is printed i am not understanding how this is happening

Roh1
  • 43
  • 1
  • 7
  • Variable names take precedence over function names. So once you declare `var foo = ` it overrides the function. https://stackoverflow.com/questions/13156209/why-does-local-variable-names-take-precedence-over-function-names-in-javascripts – daddygames Dec 10 '20 at 17:12
  • Just don't use multiple functions with the same name. The one that logs `foo 3` will always overwrite the one that logs `foo 1`. – Bergi Dec 10 '20 at 17:14
  • @daddygames You need to distinguish between the variable declaration (`var foo`), which does not take precedence but simply gets absorbed by the function declaration, and the assignment which does overwrite the value of the variable no matter how it was declared. – Bergi Dec 10 '20 at 17:16

0 Answers0