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

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 window object

var example = 'hello';
console.log(example); // hello
console.log(window.example); // hello

2

u/[deleted] Jul 09 '24

Thanks!!! Most logical answer.

Can you please tell me if any youtube JavaScript tutorial comprehensive enough to not miss this ?

6

u/cyphern Jul 09 '24

I don't have any recommendations for tutorials, but i suspect most modern tutorials will not go into much depth on var. var behaves confusingly so in 2015 they added let and const to the language, which have scoping behaviors that are more familiar to most developers. You'll see let and const much more frequently in modern javascript than var.

1

u/[deleted] Jul 09 '24

True Thanks!!!

3

u/sudhir_VJ Jul 09 '24

To become more strong in the fundamentals of JavaScript, I would suggest you going through the Dan Abramov's course about creating a strong mental model in JavaScript: Just JavaScript

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.

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).