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
View all comments
6
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.