Understanding Scope, Hoisting, and Closures like a Pro!
πΉ What is Scope? Scope defines the accessibility of variables in your code. Simply put: Scope decides where in your code a variable can be used. In JavaScript, every variable has a βboundary.β Out...

Source: DEV Community
πΉ What is Scope? Scope defines the accessibility of variables in your code. Simply put: Scope decides where in your code a variable can be used. In JavaScript, every variable has a βboundary.β Outside this boundary, the variable is unavailable. Why is Scope important? Prevent variable conflicts Manage memory efficiently Make code predictable Main types of Scope: Global Scope β accessible from anywhere Function Scope β accessible only within a function Block Scope β accessible within {} (using let or const) Lexical Scope β determined by the codeβs written structure πΉ Scope Example let person = [1,2,3,4,5]; // global scope function total(num1, num2) { const result = num1 + num2; // function scope if(true) { var result1 = num1 * num2; // function scope (var) } console.log(result1); // accessible console.log(person); // global access } total(10, 20); console.log(result); // β Error, function scope Takeaways: result is not accessible outside the function result1 is accessible inside funct