I am trying to understand the order of execution in javascript. Why is it that foo in the body has priority over foo in the head. Is it not the foo in the head that is compiled first?
<head>
<meta charset="UTF-8">
<title>Hello</title>
<script type="text/javascript">
function foo() {
greeting = "hello from the head";
alert(greeting);
}
</script>
</head>
<body>
<div id="clickMe" onclick="foo()">Click me</div>
<script>
function foo() {
greeting = "hello from the body";
alert(greeting);
}
</script>
</body>
</html>
Later function declarations overwrite older function declarations. The older function can still be called before the newer function has been declared:
<script type="text/javascript">
function foo() {
greeting = "hello from the head";
alert(greeting);
}
foo();
</script>
<div id="clickMe" onclick="foo()">Click me</div>
<script>
function foo() {
greeting = "hello from the body";
alert(greeting);
}
</script>
but once the lower script tag runs, the function name is reassigned. It might make more sense if you look at it like this, with each function reassigning window.foo
:
<script type="text/javascript">
window.foo = function foo() {
greeting = "hello from the head";
alert(greeting);
}
</script>
<div id="clickMe" onclick="window.foo()">Click me</div>
<script>
window.foo = function foo() {
greeting = "hello from the body";
alert(greeting);
}
</script>