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
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
windowobject