-1

I have a package.json file that contains the line "type": "module",. This line triggers errors when running node a_script.js. Its as if the default parameter functionality of ECMAScript is inactivated.

// a_script.js
const doThing = (foo = "A", bar = "B") => {
  console.log(foo);
  console.log(bar);
}

doThing(foo="AYE")              // Out: AYE\nB
doThing(bar="BEE")              // Out: A\nBEE
doThing(foo="AYE", bar="BEE")   // Out: AYE\nBEE
doThing()                       // Out: A\nB

Removing "type": "module", from package.json allows the script to run without errors. The error in question is,

dothing(foo="AYE")
           ^

ReferenceError: foo is not defined

What is the reason for this?

4
  • 3
    when using modules, code is "strict" - so, yes, foo is undeclared variable Commented Jul 2, 2024 at 9:27
  • doThing(bar="BEE") // Out: A\nBEE - really? Commented Jul 2, 2024 at 9:28
  • Nope, you're right, @JaromandaX My mistake. That line produces BEE\nB
    – erikejan
    Commented Jul 2, 2024 at 9:29
  • 1
    exactly - the foo= and bar= in the function calls don't do what you thought they did - if you let foo, bar before all those function calls, then your code will work, again, not doing what you think it's doing - also, if you "use strict" at the top of the file, you'll see it fail when in commonjs mode Commented Jul 2, 2024 at 9:30

1 Answer 1

-1

As @Jaromanda X states in their comment,

when using modules, code is "strict" - so, yes, foo is undeclared variable

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.