M
M
mobileDeveloper2014-08-27 15:01:01
JavaScript
mobileDeveloper, 2014-08-27 15:01:01

Different javascript interpreter behavior in Chrome and Firefox?

A colleague accidentally stumbled upon the following difference in how browsers work. The latest versions are being used.
The code:

<html>
    <head>
        <script>
            function test() {
                functionExpressionOrFunctionDeclaration();
                
                if (true) {
                    function  functionExpressionOrFunctionDeclaration()  {
                        console.log('run');
                    }
                }
            }
            
            test();
        </script>
    </head>
</html>

Chrome will output 'run'.
Firefox (IE11 too) will throw 'ReferenceError: functionExpressionOrFunctionDeclaration is not defined'.
The documentation https://developer.mozilla.org/en-US/docs/Web/JavaS... says why this happens.
"A function declaration is very easily (and often unintentionally) turned into a function expression."

I always thought that in this case the behavior of Chrome is correct, but now I doubt it, and I could not find an answer in the ECMAScript specification.
Which browser is behaving correctly?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
Lynn "Coffee Man", 2014-08-27
@mobileDeveloper

Here it is broken down in detail.
dmitrysoshnikov.com/ecmascript/en-chapter-5-functi...
Formally, both are right, because this situation is not defined by the standard

E
Evgeny Petrov, 2014-08-27
@Petroveg

I am on the side of FF in the issue of the impossibility of the appearance of FD in the block of instructions. If it's called a statement block, then the declaration doesn't belong there.

M
mobileDeveloper, 2014-08-27
@mobileDeveloper

@Lynn gave the correct link to Dmitry Soshnikov, only I can't select his comment as the correct answer.

A
Alexander Keith, 2014-08-27
@tenbits

Here for similar things also there is "use strict". With it, you will get a "SyntaxError" since a function declaration cannot be in statement blocks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question