Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between window[] and eval() - Javascript

Tags:

javascript

I've been using both in javascript ... really don't know the difference. Googling always shows results for the "window object" or "opening a new window in javascript" so couldn't find anything there.

 eval("v"+e)
 window["v"+e]

Sometimes window works for me and at other times eval works ....

So what's the difference between eval() and window[] ?

Sorry for the newbie question though !

Norman

like image 946
Norman Avatar asked Jul 20 '10 20:07

Norman


People also ask

What is window [] in JavaScript?

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of javascript. The javascript objects are string, array, date etc.

Which is faster eval () or new function?

`Function() is a faster and more secure alternative to eval().

Why we should not use eval in JavaScript?

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension.

What is eval () function?

The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2. If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function.


2 Answers

Another point that has not been addressed is that eval will resolve the variable reference using the caller variable environment, for example:

var foo = "global";

(function () {
  var foo = "local";
  alert(eval("foo")); // alerts "local"
  alert(window["foo"]); // alerts "global"
})();

So as you can see, is not completely equivalent.

If you simply want to reference a global variable, I would recommend you to use the window[prop] approach and avoid surprises.

like image 55
Christian C. Salvadó Avatar answered Oct 06 '22 01:10

Christian C. Salvadó


eval() interprets arbitrary javascript statements, whereas with window you are accessing a property of the window object.

In your example, you seem to be using a property name in both eval() and window[]. As the global scope in a browser is the same as the window object's scope they will evaluate to the same thing.

You can think of your eval("v"+e) statement as being equivalent to eval("window['v'" + e +" ]").

like image 40
Paul Grime Avatar answered Oct 06 '22 01:10

Paul Grime