Hoisting Findings - wongsrila/intern-match GitHub Wiki

Hoisting betekent dat ongeacht waar functies en variabelen worden gedeclareerd, ze naar de top van hun scope worden verplaatst, ongeacht of hun scope globaal of lokaal is. Wat wel opvallend is, is dat alleen de declaratie van een functie of variable naar boven wordt geschoven en niet de waardes die daar aan hangen.

hier hebben we een voorbeeld:

const a = 'first;
const b = 'second;

console.log(a); // logt 'first'

Wat hier gebeurd is dat de declaraties van de variabelen als eerst naar boven worden gehaald in het document. Dus JavaScript weet alle variabele namen. Vervolgens logt je var a === 'first'. Dit is allemaal niet zo heel spannend.

Maar stel je doet het volgende:

const a = 'first;
const b = 'second;

console.log(c); // logt 'undefined' en niet ReferenceError

const c;

Het gekke is dat JavaScript wel de variabele c kent terwijl het na de console.log(c) komt. Dit komt dus door hoisting. Het eerst wat JavaScript doet met dit document is de variabelen naar boven halen.

En als we een waarde aan c meegeven:

const a = 'first;
const b = 'second;

console.log(c); // logt nog steeds 'undefined' en niet 'third'

const c = 'third';

Waarom logt het document niet 'third'? Dit komt dus omdat hoisting alleen de declaratie naar boven haalt en niet de waarde die eraan hangt. als je het volgende doet krijg je wel 'third' als output:

const a = 'first;
const b = 'second;

c = 'third';

console.log(c); // logt nog nu wel 'third'

const c;

Bronnen

Dani Krossing. (2018, 4 juni). 18: Hoisting in JavaScript Explained | What is Hoisting in JavaScript | JavaScript Tutorial. YouTube. https://www.youtube.com/watch?v=ppMlvGMT2qE

Ram, P. (2019, 29 augustus). A simple guide to help you understand closures in JavaScript. Medium. https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4