Search code examples
javascriptglobal-variables

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

Solution

  • 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.