JS होइस्टिंग
In this page:
functionName(); // works: declarations are hoisted
function functionName() { }
console.log(variable); // undefined: var is hoisted
var variable = value;
Hoisting क्या है?
Hoisting का मतलब है कि JavaScript code चलाने से पहले declarations को process करता है। व्यवहार declaration के type पर निर्भर करता है।
Hoisting को समझना इसलिए मायने रखता है क्योंकि यह बताता है कि ऐसा code जो ReferenceError के साथ fail होना चाहिए था असल में क्यों चलता है (बस अनपेक्षित values के साथ)।
उदाहरण: What Is Hoisting?
console.log(typeof laterFunction); // "function" - hoisted
function laterFunction() {}
var Hoisting
एक var declaration hoist होती है और अपने assignment के चलने तक undefined value से शुरू होती है।
इसी वजह से, किसी var-declared variable को उसकी assignment line से पहले पढ़ना error के बजाय undefined देता है, जो उन bugs को छुपा सकता है जहाँ आप उसे initialize करना भूल गए थे।
उदाहरण: var Hoisting
console.log(x); // undefined, not an error
var x = 5;
let और const
let और const भी hoist होते हैं, पर वे अपनी declaration तक पहुंचने तक temporal dead zone में रहते हैं।
किसी let/const variable को उसकी declaration line से पहले access करना undefined return करने के बजाय एक ReferenceError देता है, इसीलिए इस बीच वाली state को temporal dead zone कहा जाता है।
उदाहरण: let and const
try {
console.log(y); // ReferenceError: temporal dead zone
} catch (e) {
console.log(e.message);
}
let y = 5;
Function Hoisting
Function declarations को उनकी declaration से पहले कॉल किया जा सकता है। Function expressions वैसे काम नहीं करते।
इसका मतलब है कि आप readability के लिए helper function declarations को उनके इस्तेमाल की जगह से नीचे organize कर सकते हैं, जबकि किसी variable को assign किए गए function expressions इसके बजाय normal variable hoisting rules फॉलो करते हैं।
उदाहरण: Function Hoisting
sayHi(); // works, function declarations are fully hoisted
function sayHi() {
console.log("Hi!");
}
// sayBye(); // TypeError, sayBye is undefined here
var sayBye = function () { console.log("Bye"); };
Best Practices
Variables को इस्तेमाल करने से पहले declare करें। यह code को पढ़ने में आसान बनाता है और confusing hoisting व्यवहार से बचाता है।
Modern linters use-before-declaration को अपने आप flag करते हैं, जो एक और कारण है कि variables को पहले declare करने के बजाय hoisting पर निर्भर रहना एक खराब practice माना जाता है।
उदाहरण: Best Practices
// Best practice: declare before use
let total = 0;
total = total + 5;
console.log(total);
- किसी
letयाconstvariable को उसकी declaration से पहले इस्तेमाल करना, जो temporal dead zone की वजह सेReferenceErrorthrow करता है। - यह उम्मीद करना कि कोई
varassignment line से पहले अपनी value रखेगा, जबकि hoisting सिर्फ declaration को move करता है, इसलिए यहundefinedहोता है। - किसी function expression जैसे
const f = function() {}को उसके define होने से पहले कॉल करना, जोTypeErrorयाReferenceErrorthrow करता है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: