Junior
Mis on ulatus JavaScriptis?
sobes.tech AI
Vastus AI-lt
Scope in JavaScript is the context in which variables and functions are defined and accessible.
Simply put, it determines where in the code you can refer to a variable or function.
There are several types of scope:
- Global Scope: Variables declared outside of any function are in the global scope. They are accessible from anywhere in the code.
// Global variable let globalVar = "I am visible everywhere"; function showGlobal() { console.log(globalVar); // Accessible inside the function } showGlobal(); - Local (Function) Scope: Variables declared inside a function are in the local scope of that function. They are only accessible within that function and its nested functions, but not outside.
function showLocal() { // Local variable let localVar = "I am only visible here"; console.log(localVar); } showLocal(); // console.log(localVar); // Error: localVar is not defined - Block Scope: Introduced in ES6 (ES2015) with
letandconst. Variables declared withletorconstinside curly braces ({}), such as in code blocks, loops, or conditional statements, have block scope. Variables declared withvardo not have block scope.if (true) { // Block scoped variable let blockVar = "I am only visible in this block"; console.log(blockVar); } // console.log(blockVar); // Error: blockVar is not defined for (let i = 0; i < 2; i++) { // Loop block scope variable console.log(i); } // console.log(i); // Error: i is not defined (if `let` was used)
It is also important to understand the concept of Scope Chain. When JavaScript tries to find the value of a variable, it first looks in the current scope. If it is not found there, it moves to the outer (parent) scope, and so on, up to the global scope. If the variable is not found even in the global scope, a ReferenceError is thrown.