0

I am learning Javascript and have some Python experience. The below confuses me massively. How is it that you can call a function before it has been defined?

My assumption is that check_user_age() would not work because it is not defined until further down the script.

How does this work?

'''
<!doctype html>
<html>

<body onload="check_user_age()" style="position:absolute">
    <h1>Spiritueux Wines and Liquors</h1>
    <script>
        function check_user_age() {
            if (age_of_user() < 18)
                alert("You are too young to buy alcohol.");
        }

        function age_of_user() {
            var age = prompt("What is your age?");
            return age;
        }
    </script>
</body>

</html>
'''
Connor
  • 31
  • 3

1 Answers1

0

@CertainPerformane have already answered the question , but there is one more catch here. output from the prompt is a string.Though comparison operator like < & > will coercive the the value to primitives but better use parseInt to convert to number and then compare

function check_user_age() {
  if (age_of_user() < 18)
    alert("You are too young to buy alcohol.");
}

function age_of_user() {
  var age = prompt("What is your age?");
  return parseInt(age, 10);
}
<body onload="check_user_age()" style="position:absolute">
  <h1>Spiritueux Wines and Liquors</h1>
</body>
brk
  • 48,835
  • 10
  • 56
  • 78