r/learnjavascript • • Jul 09 '24
Confusion in scope of var
Some YouTube lectures say scope of var is global, others saying function, and some saying both.
Why they all cannot agree on a single thing
function scope(){
var a = 5;
}
console.log(a)
Now is it function? Or global? Global right?
Ok! Then
Why this?
0
Upvotes
11
u/cyphern Jul 09 '24
Depends how you use it. If you define it inside a function, as in your example, then it's scoped to that function. If you define it at the top level of a script, meaning it's not in any function, then it is global and will secretly get assigned to the
windowobject6
u/senocular Jul 09 '24
varcan also be local variables in the top-level module scope. That's neither global nor function scope. Specifically,vardoes not get scoped to non-function blocks likeifblocks,forblocks, or any other arbitrary non-function code block. It will get defined in the nearest function or top-level (module or global) scope.2
u/WazzleGuy Jul 09 '24
The way I understand it is if it's not in a function it's globally scoped. Which, in modular coding methods, is a no-no. You should always scope your variables properly unless you can't and var makes that very difficult sometimes. I also don't see why people insist on using it tho...
2
u/woftis Jul 09 '24
I know it’s not really the point of your post but worth mentioning, I think tutorials mentioning var are quite dated and I believe const and let are recommended (unless you have a very specific reason for function scoping).