JS Scope

There are three things (maybe more) that you need to know about scope, which is global/current scope
lexical scope, scope chain

Scope

Scope is variable access

Scope is the set of rules that determines where and how a variable (identifier) can be looked-up. Basically Scope is variable access. Also every function has it’s inner scope and variables inside the function can only be accessed inside the function.

Here’s an example

1
2
3
4
5
6
7
8

var a = 1; //parent
function foo(){
var b = 2;//child
}

foo(); //1
b //error

The child scope has access to a, but the parent scope does not have access to b.

https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/fig1.png

lexical(static) scope is scope that is defined at lexing time. In other words, lexical scope is based on where variables and blocks of scope are authored, by you, at write time, and thus is (mostly) set in stone by the time the lexer processes your code.