nomwery geqoilu
nomwery geqoilu

Reputation: 109

Why can I call functions declared later in the same script block, but not ones declared in later script blocks?

I use this below cod and it works as expected:

<script>
  function_two();
  function function_two() {
    alert("The function called 'function_two' has been called.");
  }
</script>

But when I apply to this code below, it doesn't work as expected:

<script>
  function_two();
</script>

<script>
  function function_two() {
    alert("The function called 'function_two' has been called.");
  }
</script>

Can someone say why?

Upvotes: 1

Views: 65

Answers (2)

Markai
Markai

Reputation: 2098

Due to the hoisting of javascript, declarations always get shoved to the top of a scope before execution (you can't see that, js does that itself). That's why you can use the function in your first example before you declared it.

In your second example you use seperate script elements for function declaration and usage. That is not possible, since the first script element get's compiled and executed before the browser starts to compile the second one.

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128776

This is because of function declaration hoisting. function declarations are hoisted to the top of the script. In the first case, what has actually happened is this:

<script>
  function function_two() {
      alert("The function called 'function_two' has been called.");
  }

  function_two();
</script>

The function declaration has been hoisted above the function_two() call.

In the second case, function_two() is contained within a different script element, and the function declaration cannot be hoisted above it - the code in this case remains in the same order, and function_two() ultimately doesn't exist when it is called.

Upvotes: 7

Related Questions