Home >Web Front-end >JS Tutorial >Javascript Hoisting
In JavaScript, you can use a variable before declaring it. This is called "hoisting". The declaration is moved to the top, so the variable is recognized even if it's used earlier.
In JavaScript, there are two types of hoisting:
NOTE:
let and const variables are not hoisted in the same way as var variables. They are still hoisted, but they are not initialized until they are declared, so trying to access them before they are declared will result in a ReferenceError.
Function hoisting in JavaScript only works for:
Function declarations: Functions declared using the function keyword, like this: function myFunction() { ... }
It does not work for:
Function expressions: Functions assigned to a variable, like this: var myFunction = function() { ... }
Arrow functions: Functions declared using the arrow syntax, like this: var myFunction = () => { ... }
So, only plain function declarations are hoisted in JavaScript.
Variabel Hoisting Example:
// Using the variable before declaring it console.log(x); // Output: undefined // Declaring the variable var x = 10;
In this example, even though x is used before it's declared, the code doesn't throw an error. Instead, x is logged as undefined. This is because the variable declaration is hoisted to the top.
Function Hoisting Example:
// Calling the function before it's declared myFunction(); // Declaring the function function myFunction() { console.log("Hello, world!"); } // Output: "Hello, world!"
In this example, even though we call myFunction() before it's declared, the code still works because the function declaration is "hoisted" to the top of the scope.
then give me "Could include a quick "best practices" section" for it
// Using the variable before declaring it console.log(x); // Output: undefined // Declaring the variable var x = 10;
// Calling the function before it's declared myFunction(); // Declaring the function function myFunction() { console.log("Hello, world!"); } // Output: "Hello, world!"
function example() { // Recommended approach let x, y, z; // Rest of your code }
// Recommended let count = 10; const MAX_SIZE = 100; // Avoid var unpredictableVariable;
// Good: Clear and predictable function calculateTotal() { // Function logic } calculateTotal(); // Avoid: Relies on hoisting calculateTotal(); // Risky function calculateTotal() { // Function logic }
Pro Tips
- Always aim for code clarity
- Understand hoisting, but don't rely on it as a coding technique
- Write code that is self-explanatory and predictable
The above is the detailed content of Javascript Hoisting. For more information, please follow other related articles on the PHP Chinese website!