2
<html>
    <head>
    </head>
    <body>
        <script>
            function wow(){
               alert(1);
            }
            wow();

            function wow(){
                alert(2);
            }
            wow();
        </script>
    </body>
</html>

This is my code, I expect it will alert 1 and 2 but instead, it alerted 2 and then 2 again, why????

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
dramasea
  • 3,370
  • 16
  • 49
  • 77
  • [jsfiddle](http://jsfiddle.net/abc123/XAeyy/) to demonstrate `alert(2)` followed by `alert(2)` – abc123 Feb 22 '14 at 08:06

3 Answers3

6

Function declarations are hoisted. It doesn't matter where you put them*: they are processed before anything else.

Function expressions, on the other hand, are not hoisted.

var wow;
wow = function (){ alert(1); };
wow();
wow = function (){ alert(2); };
wow();

* within the scope (parent function or global) that they appear in.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • how if i put and execute the function inside for loop? for(var i =1 ; i< 3; i++) – dramasea Feb 22 '14 at 08:07
  • I wonder if "hoisting" is the correct term when applied to functions? – Pavlo Feb 22 '14 at 08:07
  • 1
    @Pavlo — it is. It isn't a term used by the ECMAScript specification at all though. – Quentin Feb 22 '14 at 08:08
  • @dramasea — Function declarations would still be hoisted, function expressions wouldn't, but the function would be identical each time you went around the loop anyway. (Although see [this question](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example)). – Quentin Feb 22 '14 at 08:10
0

This is an effect of how you are declaring the functions. All of the function declarations are evaluated first before the code that uses them.

You can get your intended effect by declaring the functions as function expressions instead:

<html>
    <head>
    </head>
    <body>
        <script>
            var wow = function (){
               alert(1);
            }
            wow();

            wow = function (){
                alert(2);
            }
            wow();
        </script>
    </body>
</html>
Krease
  • 15,805
  • 8
  • 54
  • 86
-1

Because function declarations are available before any execution context is ran.

joshkurz
  • 1,033
  • 7
  • 12