Understanding the scope of variables in Javascript
Scope determines the accessibility of variables from different parts of your code.
JavaScript has two types of scopes: Global scope and Local scope.
Global scope:
When a variable is ''globally scoped'', that variable is available from anywhere in your program. If the variable is declared outside a function or a block outside a function, leads to it being a globally scoped.
Local scope :
When variables are declared within a function or a block, they are locally scoped. It means that they can only be accessed inside the function or the block they were declared in.
Local scope variables are divided into:
- Function scoped variables: a function scoped variable means that the variable defined within a function will not be accessible from outside the function.
- Block scoped variables: a block scoped variable means that the variable defined within a block will not be accessible from outside the block. A block can reside inside a function, and a block scoped variable will not be available outside the block even if the block is inside a function.
There are three different keywords used to declare a variable in JavaScript. These are: var, let and const.
Var is function scoped, let and const are block scoped.
Here are some examples about var and let: