Basic Javascript - Global Scope and Functions Question

In this lesson it says

" Variables which are declared without the let or const keywords are automatically created in the global scope"

This implies that variables which are declared with the ‘var’ keyword are automatically created in the ‘global’ scope. One further implication is that variables declared with the ‘var’ keyword inside of functions are created in the global ‘scope’. But is this true?

I am seeing other sources online saying that variables declared with the ‘var’ keyword within a function have local function scope.

For example, w3schools says:

"Variables declared with var, let and const are quite similar when declared inside a function.

They all have Function Scope"

But then they also say:
" Variables declared with the var keyword can NOT have block scope."

But is function scope not an instance of block scope?

Looking for clarification on what I’m misunderstanding, thanks in advance!

var should not be used as it is outdated. You only want to use either let or const, you will find out in later lessons that var is quickly dropped. It is introduced just in the earlier lessons

var would not be considered block scope because it could be used outside of the block it was declared in. let or const are block scope because they can only be used in the block they are declared in. Thats the difference, but again var should not be used if you work on your own projects.

That is true, var is function scoped.

function testScope() {
  var a = "test";
}

testScope();

console.log(a); // ReferenceError: a is not defined
console.log(globalThis.a); // undefined

Unless it isn’t inside a function, then it is global.

var testVar = 'test';
let testLet = 'test';
console.log(globalThis.testVar) // test
console.log(globalThis.testLet) // undefined

You can consider a function as one kind of block scope. But because it is only inside a function it is a function scope, not a block scope.

A block scope is any code block.

{
  let test = "test";
}
console.log(test); // ReferenceError: test is not defined
{
  var test = "test";
}
console.log(test); // test

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.