
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.” 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 functio
Continue reading on Dev.to
Opens in a new tab

.png&w=1200&q=75)