DEV Community

Giyeon Kwon
Giyeon Kwon

Posted on

Can somebody help me with React?

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

// MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init

  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.. 😫
  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>
  );
}
  1. 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)

Collapse
 
merichard123 profile image
Richard • Edited

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

developer.mozilla.org/en-US/docs/G...

Collapse
 
giyeonkwon profile image
Giyeon Kwon

It says “Declarations using let and const are also not hoisted.“ ☹️

Collapse
 
merichard123 profile image
Richard

Ah ok. Didn't know es6 declarations aren't hoisted

Collapse
 
varjatua profile image
Bohdan

If you got undefined - probably you should look into webpack/babel. I think that your const was transpiled to var

Collapse
 
giyeonkwon profile image
Giyeon Kwon

That makes sense! Thank you.😃

Collapse
 
amt8u profile image
amt8u

Agree. And to verify you can disable sourcemap in webpack settings and checkout the actual transpiled code that runs in the browser.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
giyeonkwon profile image
Giyeon Kwon

It surly works! but my question is "can access lexical declaration `variable' before initialization" in React. 😢

Collapse
 
siddaiahm profile image
Siddaiah M

Can you please tell , where you got undefined as output , I mean in your terminal or in the chrome when running app.

Thread Thread
 
giyeonkwon profile image
Giyeon Kwon • Edited

I got "undefined" in the chrome console when running react-app.

you could check in my codesandbox
codesandbox.io/s/strange-brook-ii0...

Thread Thread
 
siddaiahm profile image
Siddaiah M

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.