0

So I was practicing javascript and I wrote the following code

function fun1(){
    globalVar = 5;
}
function fun2(){
console.log(globalVar);
}
fun2();

I am using vs code and I run the above code using node and it says that globalVar is undefined, I don't understand global variables well so a brief explanation would be appreciated.

1
  • 2
    You didn't run fun1() to assign to the global. Commented May 28, 2021 at 10:06

3 Answers 3

1

You did not run fun1()

function fun1(){
    globalVar = 5;
}
fun1();
function fun2(){
console.log(globalVar);
}
fun2();

Sign up to request clarification or add additional context in comments.

Comments

0

You are missing declaration of the globalVar variable. Add

let globalVar;

above the function fun1().

1 Comment

fun1 is not calling thats why it show undefined, if he set let globalVar; but not run fun1 then still he will get undefined
0

The fact that in func2 you have globalVar = 5; and not var|let|const globalVar = 5; causes JavaScript to treat globalVar as a global variable. However, since you do not call func1, when globalVar is seen in func2 it is indeed still undefined.

If you add a call to func1 before calling func2, then by the time console.log is executed globalVar will be defined. Although if you are in strict mode, you will get an error complaining about trying to assign a value to an undefined variable (in func1). So, you'd better have a `var globalVar;' at the very top.

So, in essence

  • if you have an assignment inside a function and the variable is not preceded with a var|let|const qualifier it is assumed to be a variable defined in the global scope,
  • if the variable is defined in the global scope all is good; if it is not, if you are in strict mode (if your code begins with "use strict";), then there will be an error. If you are not in strict mode the variable will be defined in the global scope and execution continues.

Comments

Your Answer

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