Skip to main content

Scope in JavaScript

 


Scope determines the accessibility of variables, functions, and objects in different parts of your code. In JavaScript, scope can be global, function, block, or module level.

1.1 Types of Scope

1.1.1 Global Scope

  • Variables declared outside any function or block have global scope.

  • Accessible from anywhere in the code.

var globalVar = "I am global"; function showVar() { console.log(globalVar); // Accessible here } showVar(); console.log(globalVar); // Accessible here too

1.1.2 Function Scope

  • Variables declared inside a function using var are function-scoped.

  • Only accessible inside the function.

function test() { var x = 10; console.log(x); // 10 } console.log(x); // Error: x is not defined

1.1.3 Block Scope

  • Variables declared with let or const inside {} are block-scoped.

  • Only accessible inside that block.

{ let a = 5; const b = 10; console.log(a, b); // 5, 10 } console.log(a, b); // Error: a and b are not defined

1.1.4 Lexical Scope

  • Scope determined by where functions are declared, not where they are called.

function outer() { let x = 10; function inner() { console.log(x); // inner can access x } inner(); } outer(); // 10

2. Hoisting in JavaScript

Hoisting is JavaScript's behavior of moving declarations to the top of their scope before code execution.

  • Only declarations are hoisted, not initializations.

  • var variables and function declarations are hoisted.

  • let and const are hoisted but are in the Temporal Dead Zone (TDZ) until they are initialized.

2.1 Hoisting with var

console.log(a); // undefined (only declaration hoisted) var a = 5; console.log(a); // 5
  • Explanation: var a; is hoisted to the top, but a = 5 remains in place.

2.2 Hoisting with let and const

console.log(b); // ReferenceError: Cannot access 'b' before initialization let b = 10; console.log(c); // ReferenceError: Cannot access 'c' before initialization const c = 20;
  • Variables are in TDZ from the start of the block until initialized.

2.3 Hoisting with functions

Function Declaration

  • Fully hoisted (can be called before declaration):

sayHello(); // Hello function sayHello() { console.log("Hello"); }

Function Expression

  • If assigned to var, only variable declaration is hoisted, not the function:

greet(); // TypeError: greet is not a function var greet = function() { console.log("Hi"); };
  • If assigned to let or const, it behaves like block-scoped variable in TDZ.


3. Scope and Hoisting Together

  • var: function-scoped, hoisted → accessible before initialization (undefined).

  • let / const: block-scoped, hoisted → not accessible before initialization (TDZ).

  • functions: declaration hoisted → can be called before definition.

console.log(x); // undefined var x = 5; console.log(y); // ReferenceError let y = 10; foo(); // Works function foo() { console.log("Function hoisting"); } bar(); // TypeError: bar is not a function var bar = function() { console.log("Function expression"); }

4. Key Points

  1. Hoisting moves declarations, not initializations.

  2. var → function scope, initialized as undefined.

  3. let and const → block scope, in TDZ until defined.

  4. Function declarations → fully hoisted.

  5. Function expressions → only the variable is hoisted (not the function body).

  6. Scope determines where variables and functions are accessible.

  7. Lexical scope is resolved at compile time, not runtime

Comments

Popular posts from this blog

Use Ref

  in case of useref no need to deal with vdom directly real dom of browser is updated Venice That's a fantastic observation, and you're touching on the core power of  useRef . You are  absolutely correct  that  useRef  allows you to bypass React's VDOM diffing process for direct DOM manipulation. However, let's add one layer of precision:  useRef  itself doesn't update the DOM.  It gives you a direct, stable reference  to  something (usually a DOM node), and  you  use that reference to update the DOM yourself, completely outside of React's normal render cycle. Let's contrast the two flows. The  useState  Flow (The "Official" React Way) This is the "ask for permission" model. Trigger:  You call  setCount() . Render:  React schedules a re-render. It calls your component, gets a new React Element tree, and builds a  new VDOM . Reconciliation (Diffing):  React compares the new VDOM to the old...

Ternary operator and its working on mechanism on array

  If condition is true → use valueIfTrue If condition is false → use valueIfFalse ✅ Your amenity example Your code: {amenity === 'wifi' ? 'WIFI' : amenity} Breakdown: ✔ Condition: amenity === 'wifi' This checks: “Is the current amenity equal to 'wifi'?” ✔ If condition is TRUE → show: 'WIFI' ✔ If condition is FALSE → show: amenity 🎯 Example with your amenitiesList const amenitiesList = [ 'wifi' , 'parking' , 'kitchen' ]; Looping through each item: 🔹 1. amenity = "wifi" Check condition: 'wifi' === 'wifi' → TRUE So ternary returns: 'WIFI' 👉 Display: WIFI 🔹 2. amenity = "parking" Check condition: 'parking' === 'wifi' → FALSE So ternary returns: amenity // which is "parking" 👉 Display: parking 🔹 3. amenity = "kitchen" Check condition: 'kitchen' === 'wifi' → FALS...

position vs translate

  The Golden Rule 🏠 Positioning ( top , left , etc.) 👉 Moves relative to the PARENT 🚶 Translate ( translate-x , translate-y ) 👉 Moves relative to ITSELF That’s it. If you remember only this, you’ll never confuse them again. 🎯 Imagine This Real-Life Story Think of a room (parent) and a table (element) . 1️⃣ left-1/2 → Parent Based You tell someone: “Put the table so its left edge is at 50% of the room.” The room decides the position. Room Width = 1000 px 50% = 500 px Table 's left edge is placed at 500px So positioning = 📏 Room measurement 2️⃣ translate-x-1/2 → Self Based Now you say: “Move the table forward by half of its own width.” The table measures itself. Table Width = 200px 50 % = 100px It moves 100px So translate = 📦 Self measurement 🔥 Ultimate Memory Formula Positioning → Parent controls me Translate → I control myself 💡 Why Centering Needs Both When you do: left - 1 / 2 You move the left edge to center. But the e...