-
Notifications
You must be signed in to change notification settings - Fork 0
Hoisting Javascript
Hoisting is een gedraging van Javascript waarbij de definities van variabelen en functies naar de top van hun bereik worden verplaatst. Omdat var x = 100; niet als eerst gedefinieerd is, wordt de eigenlijke definitie opgeheven, niet de initialisatie(var x;), en onthoudt javascript dus de var x;. Daardoor is de output undefined.
// Attempt to use a variable before declaring it
console.log(x);
// Variable assignment
var x = 100;
Output
undefined
En als we var helemaal weghalen, en een code gebruiken als:
// Attempt to use a variable before declaring it
console.log(x);
// Variable assignment without var
x = 100;
Output
ReferenceError: x is not defined
Hier krijgen we een error door.
| Trefwoord | Scope | Hoisting | Can be reassigned | can be redeclared |
|---|---|---|---|---|
| var | Function scope | Ja | Ja | Ja |
| let | Block scope | Nee | Ja | Nee |
| const | Block scope | Nee | Nee | Nee |
Een ander voorbeeld:
// Initialize x in the global scope
var x = 100;
function hoist() {
// A condition that should not affect the outcome of the code
if (false) {
var x = 200;
}
console.log(x);
}
hoist();
Output
undefined
Als we let en const zouden gebruiken krijgen we geen undefined, deze zijn namelijke block-scoped & var is function scoped. Hoisting gebeurt niet hen, zoals hieronder te zien is.
// Initialize x in the global scope
let x = true;
function hoist() {
// Initialize x in the function scope
if (3 === 4) {
let x = false;
}
console.log(x);
}
hoist();
Output
true
Bronnen
Understanding Variables, Scope, and Hoisting in JavaScript
Sofya Gerges Productions 💜 | 2021
Speciale message voor docent front-end, Alles wat onder de kopjes Research Javascript & Eloquent Javascript Book staat is voor het vak Front-end. En de twee losse pagina's Codeplan + wireframes en Progressive Enchanchment ook.
- Template Engines
- Progressive Enchanchment Front-end:
- Formatters & Linters
- Text editors
- Command Line: Git Strategy
- Clean Code Javascript