-1

My question is why is a variable (when using var keyword) accessible outside the if statement block, but not outside the function block? Consider this code:

let age = 30;

if (true){
    let age = 40
    console.log('inside', age)  //logs inside, 40//
    var name = 'shaun'
}

console.log('outside if loop', age, name) //logs outside if loop, 30, shaun //

function test (){
    var xyz = 'ashley';
    console.log(xyz)

}
test ()

console.log('outside function', xyz) //throws an error//

Thank you for your time. Any insights would be appreciated!

LightBulb
  • 37
  • 5
  • 1
    Duplicate of: [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Dexygen Jan 25 '20 at 13:09

1 Answers1

-1

Because of the current context of execution. The context in which values and expressions are "visible" or can be referenced. If a variable or other expression is not "in the current scope," then it is unavailable for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.

A function serves as a closure in JavaScript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions.

Also ES6 does have block scope for variable definitions with the let and const keywords but not with var.

Here is an article on Wikipedia about Scope.

  • So the scope for for-loops or if-statements is considered different than the scope for functions? I thought they were all local scopes, and hence should not be accessible globally? But in my example it is clear that if-statement's local variable name is accessible outside of the statement, but the function variable is not. – LightBulb Jan 24 '20 at 17:31
  • JavaScript has no "block scope", it only has function scope - so variables declared inside an if statement (or any conditional block) are "hoisted" to the outer scope. – David Martins Jan 24 '20 at 18:05
  • Aaaah!!! This clears it for me. Thanks a ton!!! – LightBulb Jan 24 '20 at 18:26
  • _'JavaScript has no "block scope"'_ - `let` and `const` want to have a word... – Andreas Jan 25 '20 at 12:03
  • Maybe I need to learn more, you're right, seems like there was a scope change after ECMAScript 2015 (6th edition). I edited the answer. – David Martins Jan 25 '20 at 13:07