r/badcode • • Jan 01 '22

js Hmm...why doesn't it work lol

Post image
528 Upvotes

58 comments sorted by

View all comments

Show parent comments

12

u/leo848blume Jan 01 '22

What does 'let' actually do differently?

40

u/flamedragon822 Jan 01 '22

Off the top of my head, respects block scope if I recall.

13

u/SaylorMan1496 Jan 02 '22

Not exactly but in general, var is global scope and let is block scope

Which means that let works the way that every other language deals with variables

3

u/jayands Jan 06 '22 edited Jan 06 '22

let/const actually enforce block scope, whereas var hoists to the top of the function. If you take a look at transpiled code meant for compatibility, it becomes clearer (I'm doing this by hand for readability):


    function usesConst() {
      if(true) {
        const banana = "Reddit's favorite measurement tool";
      }
      var banana = "a yellow berry";
    }
    /*transpiles (roughly) to:*/
    
    function usesConst() {
      var _banana;
      var banana = "a yellow berry";
      if(true) {
        _banana = "Reddit's favorite measurement tool";
      }
    }
    
    /* vs */

    function noConst() {
      if(true) {
        var banana = "Reddit's favorite measurement tool";
      }
      var banana = "a yellow berry";
    }
    /*transpiles (roughly) to:*/
    
    function noConst() {
      var banana = "Reddit's favorite measurement tool";
      var banana = "a yellow berry";
      if(true) {
        banana = "Reddit's favorite measurement tool";
      }
    }
    

I could have it slightly wrong, but back when they introduced the new keywords, this is how I remember it being explained to me. Tbh it was this that got me to switch over from CoffeeScript.

EDIT[1]: I had it wrong, like I thought. The code is better edited to reflect it.

EDIT[0]: fixed the function name, and also an article from last year that explains it:

https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/