Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

javascript - I declared my variable with let but it is still not in global scope

I am trying to make a component appear on condition of 'uneligible=(age<18)' so I tried to declare uneligible out of his function's scope and declaring it with let because I know the value will change later

    let uneligible;
  const handleSaveGeneral = async (e) => {
    var dateOfBirth = "2007-01-01";
    var split_dob = dateOfBirth.split("-");
    var month = split_dob[1];
    var day = split_dob[2];
    var year = split_dob[0];
    var dob_asdate = new Date(year, month, day);
    var today = new Date();
    var mili_dif = Math.abs(today.getTime() - dob_asdate.getTime());
    var age = mili_dif / (1000 * 3600 * 24 * 365.25);
    console.log(age);
    uneligible = age < 18;
  };

now it's undefined in the syntax around the component and the component doesn't appear

<div>
      {uneligible && (
        <Alert variant="filled" severity="error">
          This is an error alert — check it out!
        </Alert>
      )}
    </div>

code sandox:https://codesandbox.io/s/serverless-wave-qyuc4?file=/src/App.js:602-767

I didn't use stateful variable because of that issue:conditional rendering is not working in my functional component

question from:https://stackoverflow.com/questions/65875644/i-declared-my-variable-with-let-but-it-is-still-not-in-global-scope

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

let allows you to declare variables that are limited to the scope of a block statement or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

To achieve what you want you can use var / window.uneligible instead of let


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...