I have a fundamental misunderstanding of how Javascript works, and I hope someone can explain it to me.
Everything works fine if I include a function in a script section in the head and one calling that function in the body.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function say_hello() {
document.write('hello');
}
</script>
</head>
<body>
<script>
say_hello();
</script>
</body>
</html>
If I move the same code to the body, I get an error. "Uncaught ReferenceError: say_hello is not defined"
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script>
say_hello();
</script>
<script>
function say_hello() {
document.write('hello');
}
</script>
</body>
</html>
But it works again if I put the function in the same script area.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script>
say_hello();
function say_hello() {
document.write('hello');
}
</script>
</body>
</html>
A common mantra is to move javascript to the end of the body area of HTML. But when I try to move my javascript functions, this is what happens. What am I misunderstanding?