216

Let's say I have a variable that I want to export. What's the difference between

export const a = 1;

vs

export let a = 1;

I understand the difference between const and let, but when you export them, what are the differences?

1
  • export keyword details here. Currently it is not supported natively by any of the web-browsers. Commented May 1, 2017 at 6:44

2 Answers 2

367

In ES6, imports are live read-only views on exported-values. As a result, when you do import a from "somemodule";, you cannot assign to a no matter how you declare a in the module.

However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can’t be changed
counter++; // TypeError

As you can see, the difference really lies in lib.js, not main1.js.


To summarize:

  • You cannot assign to import-ed variables, no matter how you declare the corresponding variables in the module.
  • The traditional let-vs-const semantics applies to the declared variable in the module.
    • If the variable is declared const, it cannot be reassigned or rebound in anywhere.
    • If the variable is declared let, it can only be reassigned in the module (but not the user). If it is changed, the import-ed variable changes accordingly.

Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this answer. I just did myModule.counter = "new value". As you explained it did not work. I am a bit disappointed that oxc did not find out that.
Variables are time sensitive, which can make them unpredictable. I wouldn't advise using them outside of a local scope.
1

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

1 Comment

This is not true. Assignments to the exported let variable will be seen whenever they occur, even after the exporting module has finished evaluation. See example in answer by @FelisCatus.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.