Can somebody help me with React?

giyeonkwon profile image Giyeon Kwon ・1 min read

How could it be possible to access const-variable before it was initialized in REACT app (It does NOT in Chrome Console tho!)

// MDN

  1. 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.. 😫

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
  1. Chrome Console
try {
  const test = "THIS IS FOR TEST";
} catch (error) {
  // ReferenceError: Cannot access 'test' before initialization
    at <anonymous>:2:15

Posted on by:


Editor guide

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 avoided



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 your const was transpiled to var


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

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.