Scopes
- JavaScript has 3 types of scope: Block, Function, Global
Block Scope
- Variables declared using
let
, const
inside a { }
block cannot be accessed outside of the block. Because it has block scope.
- Variables declared using
var
inside a { }
block can be accessed outside of the block. Because it has function scope
if(true) {
let i = 10;
const msg = "hi"
var a = 5;
console.log(i);
console.log(msg);
console.log(a);
}
console.log(i); //error
console.log(msg); //eror
console.log(a);
Function Scope
- Each function creates a new scope.
- Variables declared using
let
, const
, var
within a function, becomes local variable and have function scope.
- They can only be accessed from within the function and not outside the function.
- Variables with the same name can be used in different functions.
- Parameters work as local variables inside functions.
function display() {
let i = 10;
const msg = "hi"
var a = 5;
console.log(i);
console.log(msg);
console.log(a);
}
display();
console.log(i); //error
console.log(msg); //eror
console.log(a); //error
Global Scope
- A variable declared outside a function, becomes global variable and have global scope.
- All scripts and functions on a web page can access it.
- If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
- Global variables defined with the
var
keyword belong/attach to the window object:
- Global variables defined with the
let
, const
keyword doesn't belong/attach to the window object
- Function is also a global and is added to the window object.
let i = 10;
const msg = "hi"
var a = 5;
console.log(i);
console.log(msg);
console.log(a);
Avoid var
- Avoid
var
and instead use let
or const
- Don't create global variable using
var
keyword, because it gets attached to window object. If a third party library also has a variable with the same name, that variable can override your variable. So you should avoid adding stuff to the window object. Otherwise you're going to create all sorts of issues in your program