'Basic variable declaration and memory in Javascript/Vue
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rachitiitr |
