What's happening here is that you've hit the difference between a function expression and function declaration.
function myName () {
console.log ("Rich");
}
This is a function declaration, and it is subject to a javascript feature called hoisting, which moves it to the top of the scope it's declared in. This means that when you set var myName = "Richard", it actually comes afterwards in the order of execution and overwrites the function.
By contrast, myName = function() { ... } is a function expression, and it is evaluated in place, and behaves as you'd expect with your code laid out as it is.
What's happening here is that you've hit the difference between a function expression and function declaration.
This is a function declaration, and it is subject to a javascript feature called hoisting, which moves it to the top of the scope it's declared in. This means that when you set
var myName = "Richard"
, it actually comes afterwards in the order of execution and overwrites the function.By contrast,
myName = function() { ... }
is a function expression, and it is evaluated in place, and behaves as you'd expect with your code laid out as it is.I actually just wrote a post on this exact thing -- carlanderson.xyz/function-declarat...
Great answer!
Thank you for educating ! CAP