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

Tailwind css and its corresponding vanilla css

Tailwind Class CSS Property Vanilla CSS Equivalent Description bg-white background-color background-color: #ffffff; Sets background color to white. shadow-sm box-shadow box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); Adds a small shadow under the element. border-b border-bottom-width border-bottom-width: 1px; Adds a bottom border. Default color: #e5e7eb (gray-200). max-w-7xl max-width max-width: 80rem; /* 1280px */ Restricts container width for large screens. mx-auto margin-left , margin-right margin-left: auto; margin-right: auto; Centers the container horizontally. px-4 padding-left , padding-right padding-left: 1rem; padding-right: 1rem; Adds horizontal padding (16px). sm:px-6 Responsive padding (small screens ≥640px) @media (min-width: 640px) { padding-left: 1.5rem; padding-right: 1.5rem; } Increases padding on small screens. lg:px-8 Responsive padding (large screens ≥1024px) @media (min-width: 1024px) { padding-left: 2rem; paddi...

Rest and spread operator in javascript

  Absolutely 👍 — here are several practical and clear examples of the rest operator ( ... ) in JavaScript, covering functions, arrays, and objects 👇 🧮 1. Rest in Function Parameters When you don’t know how many arguments a function will receive: function multiply ( factor, ...numbers ) { return numbers. map ( n => n * factor); } console . log ( multiply ( 2 , 1 , 2 , 3 , 4 )); // Output: [2, 4, 6, 8] 👉 factor gets the first argument ( 2 ), and ...numbers collects the rest into an array [1, 2, 3, 4] . 🧑‍🤝‍🧑 2. Rest with Array Destructuring You can collect remaining array elements into a variable: const fruits = [ "apple" , "banana" , "mango" , "orange" ]; const [first, second, ...others] = fruits; console . log (first); // "apple" console . log (second); // "banana" console . log (others); // ["mango", "orange"] 👉 The rest operator gathers all remaining elements afte...

Role of box-sizing and its attributes in css

  🧱 Default behavior (content-box) By default, browsers use: box-sizing : content-box; This means: Total element width = content width + padding + border So if you have: .container { width : 300px ; padding : 20px ; border : 5px solid black; } Then the total visible width becomes: 300 (content) + 40 ( left + right padding) + 10 ( left + right border) = 350 px ⚠️ The box becomes wider than 300px , which can cause overflow or layout shifts. ✅ With box-sizing: border-box When you use: box-sizing : border-box; the formula changes to: Total element width = width (including padding + border) So the same CSS now behaves like this: width = 300 px (total) → content area = 300 - ( 40 padding + 10 border) = 250 px ✅ The box stays exactly 300px wide — no overflow. 🎯 Why it’s useful Prevents unexpected overflow due to padding/borders Makes responsive layouts easier Keeps your box sizes consistent You can trust width to be the actu...