Search code examples
javascriptvariablesmemoryallocation

Why do people use variables in some cases?


I know this question title looks scary, but it isn't. Sorry!

Ok, so, what's the point of creating a one-time-only/unchangeable "variable"?

Lets say I have one property called "name" in a Person object.

const Person = {
    name: 'Luis Felipe Zaguini'
};

Alright. So, it's incredibly common to see people doing this:

let personName = Person.name;
console.log(`I've written my name, and it is ${personName}.`);

And that's it. In the majority of times that variable is used only once. Or, sometimes, it's referenced in other statements, but you know, it's useless because there IS a way to reference it without setting a new variable.

Tecnically, you're wasting CPU memory, allocating memory for something useless because you can, in fact, type Person.name multiple times, and do this:

console.log(`I've written my name, and it is ${Person.name}.`);

Also, you're wasting time and adding more lines to your code. Am I overracting? Lot of programmers do this kind of stuff, but personally it doesn't seem to fit very well to me.


Solution

  • There are any number of reasons

    1. A 'const` variable will prevent the value from accidentally changing, e.g. if you have written a closure that includes a variable that is accessible outside immediate scope.

    2. Javascript engines are not yet capable of common subexpression elimination, which is a very common compiler optimization. Using a temporary variable could improve performance, like in this example.

    3. Sometimes a variable with a different name can clarify the functionality; see Writing Really Obvious Code (ROC). Example:

      var activeUsername = User.name;  //It's not just a user's name, it's the active user's name!
      
    4. Sometimes that extra variable makes it easier to debug/watch variables

    5. Sometimes you want to set a separate breakpoint during the assignment

    Am I overracting?

    Yes.