Hacker News new | past | comments | ask | show | jobs | submit login

Why does this use let and var together? Was I (not a modern js expert) wrong to think var is considered obsolete? Is it because OP wanted to use var's scoping rules?



It's almost certainly from copy-pasted code from other sources. The Perlin Noise section at the top is not original code at least - though I can't find an original source.

https://github.com/processing/p5.js/blob/8213eecccdff510015e...


var is not obsolete. You still need it sometimes for scoping reasons.


Could you give an example? It seems like any "var" could be replaced with "let" at a different scope.


Won't work:

    if(checkForSomething()) {
      let foo = 2;
    } else {
      let foo = 3;
    }

    console.log(foo); // won't work
But:

    if(checkForSomething()) {
      var foo = 2;
    } else {
      var foo = 3;
    }

    console.log(foo); // will work
That said, I religiously avoid "var" and just declare the variable beforehand with "let" because there are too many other gotchas with var. Less debugging headaches. And use "const" religiously as well, like C++ people do.


That's exactly what I meant by "any "var" could be replaced with "let" at a different scope":

    let foo;
    if (checkForSomething()) {
       foo = 2;
    } else {
       foo = 3;
    }


const in C++ is very different than const in JavaScript though. I guess you are well aware of that but I feel like being pedantic.

This is allowed in JavaScript:

    const foo = {bar: 1};
    foo.bar = 2;


It's not really any different if you keep in mind that foo is a reference here, and so that's what const applies to. The equivalent in C++ would be a const pointer to a non-const object.


const foo = Object.freeze({bar: 1});


You don't need var, you don't need it's weird scoping behavior.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: