scope
Introduction
Scope in JavaScript defines the accessibility of variables, objects, and functions in different parts of your code. Understanding scope is important for writing efficient and bug-free code.
This guide covers various types of scope in Javascript,
including global
, local
, block
, and function
scope, as well as basics of closures.
Global Scope
Variables declared outside any function or block have global scope, meaning they can be accessed from anywhere in the code.
globalVar
is accessible both inside the function checkScope
and in the global context.
Function Scope
Variables declared within a function are local to that function and cannot be accessed outside of it.
localVar
is only accessible within the checkScope
function.
Block Scope
Variables declared with let
or const
within a block {}
(such as if, for loop) are local to that block.
blockVar
and anotherBlockVar
are only accessible within the block they are declared in.
Closures
For in-depth guide about closures check this article: Closures in Javascript
A closure is a function that retains access to its outer scope even after the outer function has finished executing.
innerFunction
has access to outerVar
even after outerFunction
has finished executing.
Block Scope vs Function Scope
Variables declared with var
are function-scoped, while those declared with let
and const
are block-scoped.
functionScoped
is accessible outside the if block
, but blockScoped
is not.
Scope in ES6 Classes
In ES6 classes, variables can be declared within the class body, but they are scoped to the class.