java script में hosting का अर्थ होता है की declaration से पहले हम function और variable का उपयोग कर सकते है।
// using test before declaring
console.log(a); // undefined
var a = 5
ऊपर दिया गया प्रोग्राम undefined return करेगा। ऊपर दिया गया प्रोग्राम निचे दिए गए प्रोग्राम की तरह behave करेगा।
var a ;
console.log(a); // undefined
a = 5
Hoisting , java script का एक ऐसा default behavior है जो कोड के execution से पहले सारे declarations को scope के top में move कर देता है। Hositing में यह matter नहीं करता है की function class variable कहाँ declare किये गए है यह सारे declarations को scope के top में move कर देता है। चाहे scope Global हो या local।
Note: JavaScript only hoists declarations, not initializations. For example :
console.log(a);
var a = 10; // declaration or initialization
output : undefined
ऊपर दिया गया प्रोग्राम निचे दिए गए प्रोग्राम की तरह behave करेगा।
var a ; // declaration
console.log(a);
a = 5 // initialization
output : undefined
अर्थात Hoisting , declaration तो करता है लेकिन initialization नहीं।
Variable Hoisting
variable Hosting में , var कीवर्ड Hosting को allow करते है जबकि let और const Hosting को allow नहीं करते।
var keyword support Hosting
console.log(sum);
var sum=15 ;
Output : undefined
let & const keyword can’t support Hosting
console.log(sum);
let sum =15;
Output : ReferenceError
console.log(sum);
const sum=15;
Output : ReferenceError
Function Hoisting
function Hosting , function को declare करने से पहले फंक्शन को call कर सकते है।
hello ()
// call function before function declaration
function hello (){
console.log("hello ! good morning");
}
Output : hello ! good morning
Function as a expression
जब किसी functionको expression के रूप में उपयोग किया जाता है, तो error occur होती है क्योंकि केवल declarations ही hoist होती है |
hello ();
var hello = function (){
console.log("hello ! good morning");
}
Output : Type Error: greet is not a function