Guest User

Untitled

a guest
Nov 13th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. /*
  2. It could be a bit strange, but when I first time heard about ES6 block scoping, I felt very excited ;)
  3. Usually, for doing this I could use an immediately invoked function expression (IIFE).
  4. */
  5.  
  6. // Like this
  7. (function() {
  8. // Doing stuff here
  9. })()
  10.  
  11. // But now, we can use just '{}' for doing that!
  12. var a = 1;
  13.  
  14. {
  15. let a = 2;
  16. console.log(a) // 2
  17. }
  18.  
  19. console.log(a) // 1
  20.  
  21. // Anyway, if we would need an async/await block scope, we would still use an IIFE:
  22. (async function(){ await ... })()
  23.  
  24. // Another cool stuff which I would like to share is let keyword inside a block scope.
  25. // Let's assume we have a block scope with a var and let declared variables:
  26. {
  27. console.log(a); // 1
  28. console.log(b); // ReferenceError: b is not defined
  29. var a = 1;
  30. let b = 2;
  31. }
  32.  
  33. /* This example shows that accessing let-declared variable earlier than its declaration causes an error,
  34. whereas var-declared orderind doesn't matter!
Add Comment
Please, Sign In to add comment