arthuro555

let vs var: hoisting explained

Nov 9th, 2020
1,028
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function helloFunction() {
  2.     console.log(hello);
  3.     var hello = "e";
  4. }
  5.  
  6. // This will work because of hoisting. The preprocessor will move up the var/let statement while compiling, like this:
  7.  
  8. function helloFunction() {
  9.     var hello;
  10.     console.log(hello);
  11.     hello = "e";
  12. }
  13.  
  14. // The difference between let and var is where they are hoisted. let hoists up to the last {, var hoists up to the last function begin.
  15. // See those functions?
  16. function varHello() {
  17.     try {
  18.         console.log(hello);
  19.         var hello = "e";
  20.     } catch {
  21.         console.error("Error!");
  22.     }
  23. }
  24.  
  25. function letHello() {
  26.     try {
  27.         console.log(hello);
  28.         let hello = "e";
  29.     } catch {
  30.         console.error("Error!");
  31.     }
  32. }
  33.  
  34. // That's how they'll be preprocessed:
  35.  
  36. function varHello() {
  37.     var hello;
  38.     try {
  39.         console.log(hello);
  40.         hello = "e";
  41.     } catch {
  42.         console.error("Error!");
  43.     }
  44.     delete hello;
  45. }
  46.  
  47. function letHello() {
  48.     try {
  49.         let hello;
  50.         console.log(hello);
  51.         hello = "e";
  52.         delete hello;
  53.     } catch {
  54.         console.error("Error!");
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment