Scopes in JavaScript
Scopes in JavaScript are a fundamental concept to understand how the visibility and accessibility of variables is managed within your code.
Types of scopes: Link to heading
Global scope: Link to heading
- It is the widest scope.
- Variables declared with
var(currently not recommended),letorconstwithin the main code have global scope.
Example: Link to heading
var globalVar = "I am global";
function greet() {
console.log(globalVar); // Can access the global variable
}
greet();
console.log(globalVar); // Can be accessed from anywhere in the code
Function scope: Link to heading
- Variables declared with let or const within a function have local scope to said function.
- They are not accessible from outside the function.
Example: Link to heading
function introduce() {
let name = "John";
const age = 30;
console.log(name, age); // Can only be accessed inside the function
}
introduce();
// console.log(name); // Error: name is not defined
// console.log(age); // Error: age is not defined (out of scope)
Block scope: Link to heading
- Introduced with ES6 (ECMAScript 2015),
letandconstalso create block scope. - Variables declared inside blocks (with curly braces
{}) such asifstatements,forloops, etc. They are only accessible within that block.
Example: Link to heading
if (true) {
let message = "Hello";
}
console.log(message); // Error: message is not defined (outside of block)
Summary Link to heading
- It is recommended to use
letandconstto declare variables instead ofvar. letandconstcreate block scope by default.- Global variables should be avoided as much as possible, as they can cause name conflicts and make code difficult to maintain.
Keep learning about scopes to write more modular and organized JavaScript code!