How could it be possible to access const-variable before it was initialized in REACT app (It does NOT in Chrome Console tho!)
- React App
import React from "react";
import "./styles.css";
try {
console.log(test); // undefined
const test = "THIS IS FOR TEST";
} catch (error) {
// I don't understand why it doesn't throw the reference error.. 😫
console.log(error);
}
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
- Chrome Console
try {
console.log(test);
const test = "THIS IS FOR TEST";
} catch (error) {
console.log(error);
// ReferenceError: Cannot access 'test' before initialization
at <anonymous>:2:15
}
Top comments (11)
Most variables in JavaScript are hoisted which means the variable assignment and declaration are moved to the top of the code block so the
const test='THIS IS FOR A TEST'
Is moved to the top of the code block and the reference error is avoideddeveloper.mozilla.org/en-US/docs/G...
It says “Declarations using let and const are also not hoisted.“ ☹️
Ah ok. Didn't know es6 declarations aren't hoisted
If you got
undefined
- probably you should look into webpack/babel. I think that yourconst
was transpiled tovar
That makes sense! Thank you.😃
Agree. And to verify you can disable sourcemap in webpack settings and checkout the actual transpiled code that runs in the browser.
It surly works! but my question is "can access lexical declaration `variable' before initialization" in React. 😢
Can you please tell , where you got undefined as output , I mean in your terminal or in the chrome when running app.
I got "undefined" in the chrome console when running react-app.
you could check in my codesandbox
codesandbox.io/s/strange-brook-ii0...
Bro, this issue is with sandbox, it is considering hoisting for const and let as well, try running app using node in your pc/laptop you can see the error.