06 Aug JavaScript – Hoisting
In JavaScript, you can use a variable even before declaring it. By default, JavaScript moves all the declarations to the top i.e., hoisting. The declarations are moved to the current scope’s top.
The var for variable declaration
With var, you can use a variable even before declaring it. Let us see an example. We have used the var keyword for variable declaration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html> <body> <h1>Demo Heading</h1> <p>Press (F12) and check the error.</p> <script> // using a variable without declaring a = 5 var a </script> </body> </html> |
Output
The above works for the var, but won’t work for let and const keywords.
The let for variable declaration
Unlike var, you cannot use a let variable before declaring it. If you use it, a ReferenceError will be thrown. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html> <body> <h1>Demo Heading</h1> <p>Press (F12) and check the error.</p> <script> // using a variable without declaring b = 5; let b; </script> </body> </html> |
Output
ReferenceError can be seen:
The const for variable declaration
Unlike var, you cannot use a const variable before declaring it. If you use it, SyntaxError will be thrown. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<!DOCTYPE html> <html> <body> <h1>Demo Heading</h1> <p>Press (F12) and check the error.</p> <script> // using a variable without declaring b = 5; const b; </script> </body> </html> |
Output
SyntaxError can be seen:
No Comments