eslint / markdown

Lint JavaScript code blocks in Markdown documents
MIT License
391 stars 60 forks source link

error if javascript block has unnamed function #254

Closed iambumblehead closed 3 months ago

iambumblehead commented 3 months ago

to reproduce the error, apply the below patch and run the tests,

diff --git a/tests/fixtures/long.md b/tests/fixtures/long.md
index 78f2940..73cd48f 100644
--- a/tests/fixtures/long.md
+++ b/tests/fixtures/long.md
@@ -15,6 +15,10 @@ console.log(42);
 function foo() {
     console.log("Hello");
 }
+// Unnamed
+function () {
+    console.log("Hello");
+}

the error looks like this,

error  Parsing error: Unexpected token (

a workaround is to wrap the anonymous function with open and close parens

(function () {
    console.log("Hello");
})

I believe this error might be "recent" it occurred when I updated eslint from 9.0.0 to 9.4.0 and eslint-plugin-markdown from 4.0.1 to 5.0.0 but am not certain about that.

thanks for the helpful plugin :)

fasttime commented 3 months ago

Hi @iambumblehead! This behavior is intended. Note that function declarations, unlike function expressions, are required to have a name in JavaScript in most cases. So this code contains a syntax error, and it will be rejected by a browser or Node.js if you try to run it without modifications:

function () {
    console.log("Hello");
}

This is even noted it the spec: https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionobject

An anonymous FunctionDeclaration can only occur as part of an export default declaration, and its function code is therefore always strict mode code.

ESLint v9.0.0 with the default parser reports the same error you are seeing with ESLint v9.4.0. But if you were using a different parser previously, it's entirely possible that the syntax error went unnoticed.

iambumblehead commented 3 months ago

@fasttime thanks for the incredibly informative reply!