Home > Software engineering >  Basic variable declaration and memory in Javascript/Vue
Basic variable declaration and memory in Javascript/Vue

Time:05-12

I have a very basic question about declaring variable in Javascript/Vue.

function myFunction () {
  let myVars = this.myVars;
  forEach(myVars, (var) => {
    // Do something with var
  } 
}

VS

function myFunction () {
  forEach(this.myVars, (var) => {
    // Do something with var
  } 
}

I was wondering if the first style of coding would waste so much resources to the point that it affect performance in modern computer/browser?

CodePudding user response:

There's no impact on performance here. When the myFunction is called, myVars is registered in the function scope. Then you make myVars refer to this.myVars, if the value in this.myVars is an array or object, then there is no deep copy operation here. Both are referring to the same object. Finally, when the function execution completes, the scope created is destroyed so no memory leaks there.

One suggestion though is to prefer const over let over var.

  • Related