Scope in JavaScript
What is Scope?
Scope determines the accessibility of variables. Each function when invoked creates a new scope. In JavaScript there are two types of scopes:
1. Global Scope
2. Local Scope
Global scope: variables defined outside of a function or curly braces {} are in the global scope. Once you’ve declared a global variable, you can use that variable anywhere in your code.
Local Scope: variables defined inside of a function or curly braces {} are in the local scope. Once you’ve declared a local variable, these are usable only in a specific part of your code.
Note: You can use the same name of local variables in different functions. Every time when you call the function they have a different scope. So the same name can’t affect each other.
In JavaScript, there are two kinds of local scope.
- Function scope
- block scope.
Function scope: When you declare a variable inside a function, you can access this variable only within the function.
Block scope: When you declare a variable within a curly brace {}, you can access this variable only within that curly brace.
Problem Start with var keyword in block scope:
Here you can see that, even though the variable cat is in a block scope, but it still accesses it in another block. You Can fix this problem using the ‘let and const’ keyword.
Difference Between var, let, and const:
I hope this lesson provides a clear understands of how scope works in JavaScript. Hopefully, you learned something today. Happy Coding.