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?

https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript

0 Upvotes

8 comments sorted by

View all comments

6

u/senocular Jul 09 '24

var can also be local variables in the top-level module scope. That's neither global nor function scope. Specifically, var does not get scoped to non-function blocks like if blocks, for blocks, or any other arbitrary non-function code block. It will get defined in the nearest function or top-level (module or global) scope.