0

Here I have two examples of accessing global variables; basic example of my global variable

globalVar:any={
 a:5,
 b:3,
 c:4
}

Ex.1

function accesVar(){
 return this.globalVar.a*=2
}

Ex.2

 function accesVar(){
    let _var=this.globalVar.a;
    return _var*=2
    }

In this example global variable doesnt seem a good practise and I dont use them when I dont need to share variables with more than one function.Considering in general and real world(much bigger data),which would be best approach and has better performance?

Timuçin Çiçek
  • 1,516
  • 3
  • 14
  • 39
  • With all the different optimizations that engines do, I think the only answer is "it depends". –  Jun 15 '20 at 19:58
  • That said, your demo is one where the value is used only once, I would think *conceptually* that the extra variable assignment would mean extra work. But I would also guess that it would be optimized away. –  Jun 15 '20 at 19:58
  • Honestly, I doubt this would ever be the bottleneck in any large-scale application. If you are using a global at all, I don't think Ex.2 is better than Ex.1. I'd stick with Ex.1 because it's easier to understand. – zeterain Jun 15 '20 at 19:59

1 Answers1

0

Both have different importance. Example one is direct use of globle variable. Saves you extra declaration. Example two is useful when we need to use the global value many times inside the function.

govs
  • 51
  • 1
  • 6