import React from "react";
import "./styles.css";
const App = () => {
return (
<div className="App">
<h1>{test.foo}</h1>
</div>
);
};
const test = {
foo: "foo"
};
export default App;
this code is from codesandbox: https://codesandbox.io/s/declaring-variable-test-oixgo
this code run without any issue, I thought in javascript, const
and let
are not hoisted,
so It should be declared and initialized first before It is used (I thought the order of executing code is important)
But In this case, Although test
object is behind its usage, This code works without any error.
What has happened to this code?
Functions don't try to access variables until the function is called .
The function isn't called before the const
statement.
Check this example:
const App = () => { console.log("read",test.foo) }; App() const test = { foo: "foo" };
In React, all code will be read then execute component:
const App = () => { console.log("read",test.foo) }; const test = { foo: "foo" }; App()
const and let are not hoisted
That's not correct. They are hoisted, it's just that they are hoisted differently as compared to how var
does.
From the Ecmascript spec - 13.3.1 Let and Const Declarations
let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment. The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated. A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created.
Reason why your code works because App
function is called after test
object's declaration has already been processed.
To understand this better, consider the following example:
const foo = () => { console.log(test.a); }; const test = { a: "Hello" }; foo();
Above code example logs "Hello" because by the time foo
function is called, test
object's declarations has already been processed.
Now, if we move the foo
function call above the test
object declaration, you will get an error.
const foo = () => { console.log(test.a); }; foo(); const test = { a: "Hello" };
Above code example throws an error because of Temporal Dead Zone
, foo
function can't access the test
object. foo
function can only access test
object if it is called after the declaration of test
object has been executed during step-by-step execution of the code, which is what happened in the first code example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.