Why function overwriting is not allowed in ES6 modules?

Viewed 202

Please take a look at the following code;

"use strict"

function test1()
{
    // first
}

function test1()
{
    // second
}

let a=1
console.log( test1 );
<html>
<head>
    <script type="text/javascript" src="./test.js"></script>
</head>
<body>
<p>Hello World!</p>
</body>
</html>

As you can see this code is working, although the second definition of "test1" will overwrite the first one. Now take a look at the following code; (Html file is different)

"use strict"

function test1()
{
    // first
}

function test1()
{
    // second
}

let a=1
console.log( test1 );
<html>
<head>
    <script type="module" src="./test.js"></script>
</head>
<body>
<p>Hello World!</p>
</body>
</html>

This code is not working and gives you this error

"Uncaught SyntaxError: Identifier 'test1' has already been declared"

( You should run it with a local server to see the error. I cannot produce it here)

The difference is the scope. In the second example we overwrite the function in module scope which apparently is not allowed although it is allowed in global scope!!! Am I right? Can anybody explain this kind of behaviour for me?

(The same in node.js):

> node --experimental-modules --input-type=commonjs --eval 'function a(){}; function a(){}; console.log("ok");'

ok

> node --experimental-modules --input-type=module --eval 'function a(){}; function a(){}; console.log("ok");'
file://[eval1]:1
function a(){}; function a(){}; console.log("ok");
                ^
SyntaxError: Identifier 'a' has already been declared
0 Answers
Related