简体   繁体   中英

why does a javascript global variable within function show an error?

I put a global variable within numPrinter function in Javascript.
but if I don't put numPrinter(); before putting console.log(i);


it is a global variable .. global .. and also I don't understand how global variable works after numPrinter()

there's no return i; within numPrinter();

var numPrinter = function(){

    i = 30;
};

console.log(i);  // ReferenceError: i is not defined

numPrinter();
console.log(i);  // 30

Imagine you are the JavaScript engine, reading this code from the top-down:

  1. The first thing we read is the numPrinter function. There are no () present, so numPrinter is only defined but not invoked.
  2. Continuing down, the first console.log(i); is read. Calling it here results in ReferenceError: i is not defined because numPrinter still has NOT been invoked so i can't be accessed yet.
  3. Further down, we encounter numPrinter(); Here, the JS engine reads the () and invokes the numPrinter function. We now have access to i because undeclared variables always become global variables.
  4. Lastly, the second console.log(i); is read and prints out the result of 30 because i is globally accessible outside of the numPrinter function.

By default variables in js are global, so if you write smth like:

let i = 30

in your function, it will be local

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM