0

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
3
  • 1
    It appears you haven't declared i anywhere (with var or let), so when you just say i = 30 inside numPrinter, this "magically" declares i as a global variable and sets it to 30. (This is a strange quirk of Javascript that usually just causes problems, you can avoid it by using strict mode.) So the first time you log i, the variable isn't declared in any accessible scope, hence the ReferenceError - then numPrinter() "magically" creates the global i and sets it to 30. Commented Jan 19, 2019 at 14:49
  • @RobinZigmond thanks. but I don't get how numPrinter() can create the global i Commented Jan 19, 2019 at 15:06
  • As I sad, this is a "feature" (a bad one!) of Javascript (when not run in strict mode). I'm not sure how much more I can say, but here is a link to MDN where it's mentioned (3rd paragraph): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 19, 2019 at 15:27

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

Comments

-1

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

let i = 30

in your function, it will be local

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.