0

I want be able to export and then modify a object. However I am not sure if this is unexpected behavior.

test.js:

// Short syntax
export const foo = [];
foo[0] = 1;

// Long syntax
const bar = [];
bar[0] = 1;
export { bar };

index.js:

import { foo, bar } from "./test.js";

console.log("foo:" + foo); // Is it guaranteed to be [1]? Or can it be []?
console.log("bar:" + bar); // I always expect this to be [1].

This might be a foolish example but sometimes I have an object and want to register some methods/properties. I want to know if I am able to export it and then register them.

Exprove
  • 1,301
  • 2
  • 18
  • 32
  • 1
    Read: [export default thing` is different to `export { thing as default }](https://jakearchibald.com/2021/export-default-thing-vs-thing-as-default/) – Yousaf Dec 29 '21 at 13:31

1 Answers1

1

Are ES modules evaluated to their very end before export?

No. In fact, the exports are declared and registered before the module is evaluated.

However, what you actually seem to be asking is

Are ES modules evaluated to their very end before the modules importing them are evaluated?

Yes. test.js will be fully evaluated before index.js is evaluated1. It doesn't matter where in the module you place the import and export declarations.

1: with the exception of circular dependencies. In that case, a module might run before all the imported modules are evaluated, and you may run into uninitialised variables.

Is it guaranteed to be [1]? Or can it be []?

Yes, it's guaranteed to be [1] (or an exception that const foo is not yet initialised). It will never be [], the = [] and the foo[0] = 1 always execute right after each other.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375