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:
numPrinter
function. There are no ()
present, so numPrinter
is only defined but not invoked. 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. 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. 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.