I came across an example in React and I am trying to figure out how and why it works.
function MyComponent() {
return <h2>{name}</h2>
}
const name = "John";
export default MyComponent;
And in App.js, we're using this component, nothing fancy.
But I expected embedding name within MyComponent's JSX not to work due to how hoisting behaves with let and const, since they're placed in the TDZ until its declaration is reached.
I also tried a simple example in JavaScript.
function myFunc() {
console.log(name);
}
const name = "John";
export default myFunc;
And in my main.js, I import the function and simply execute it. It also works.
Which makes me think that modules go through the creation and execution phase before its content is used in another file? Or am I involving the execution context wrongly here? What's the explanation?
What matters is the order of execution, not the position in the code: MDN "temporal dead zone"
Your exact use case is described there as well:
Modules
JavaScript modules are evaluated when the code that imports them is evaluated.
(I like to think of it as if the imported code would simply be put at the location of the
importstatement before everything is executed together, which is not correct, but helps me thinking about it.)MDN "export"