Skip to content

Instantly share code, notes, and snippets.

@spamshaker
Created April 28, 2024 05:47
Show Gist options
  • Save spamshaker/cbd967af96998055f6f62bb922eeea92 to your computer and use it in GitHub Desktop.
Save spamshaker/cbd967af96998055f6f62bb922eeea92 to your computer and use it in GitHub Desktop.
How ES6 hoisting works
/**
* Hoisting does not work; The userLicenseFactory method is not hoisted to the top.
* @throws {ReferenceError} ReferenceError: Cannot access 'User' before initialization
*/
// console.log(User);
/**
* Hoisting works; The {UserFunc} method is hoisted to the top.
*/
console.log(UserFunc);
/**
* Hoisting does not work; The userFactory variable is not hoisted to the top.
* @throws {ReferenceError} ReferenceError: Cannot access 'User' before initialization
*/
// console.log(userFactory);
/**
* Hoisting works; The {userLicenseFactory} method is moved to the top.
*/
console.log(userLicenseFactory);
/**
* This constant does not get hoisted.
*/
const userFactory = () => User;
/**
* This function is hoisted.
*/
function userLicenseFactory() {
return UserLicense;
}
/**
* Hoisting does not work.
* @throws {ReferenceError} ReferenceError: Cannot access 'UserLicense' before initialization
*/
// userLicenseFactory();
/**
* This class is not hoisted.
*/
class User {
constructor() {
new UserLicense();
}
}
/**
* Hoisting does not work.
* @throws {ReferenceError} ReferenceError: Cannot access 'UserLicense' before initialization
*/
// const user = new User();
/**
* This class is not hoisted.
*/
class UserLicense {
}
/**
* This function is hoisted, hoisting works.
*/
function UserFunc() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment