0

Which of these variants is more accepted by most browsers or more recommended to use ?

window.var_name;
//or
window['var_name'];
MTK
  • 3,300
  • 2
  • 33
  • 49
  • 1
    the will return exactly the same result. Look up object vs array notation and the difference between objects and arrays in JavaScript. – Stu Jul 24 '16 at 20:34

2 Answers2

2

This doesn't make any difference - both of those ways are the ways of getting the value of the object by name.The second one is in case you want to get the value by a name which is stored in the variable (or a result of an expression).

In your case, the object is window, so you could either get that value with just var_name.

var var_name = "test";
console.log(var_name);
console.log(window.var_name);
console.log(window['var_name']);
nicael
  • 18,550
  • 13
  • 57
  • 90
1

There is no difference, it depends on coding style.

First one can be use when you know your variable name at development time e.g;

window.var_name;

while second is useful if you get variable name at run time e.g;

window[getVarNameDynamically()];
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110