A complete answer for that question would be really long. So I’ll try to explain a few things only. First, maybe most important fact, even if you declare a variable with var
, it depends where you do that. In a global scope, you implicitly would also write that variable in an object, most browsers call it window
. So for instance
// global scope
var x = 15;
console.log( window.x ); // 15
If we do the same thing within the context of a function things change. Within the context of a function, we would write that variable name into its such called ‘Activation Object’. That is, an internal object which the js engine handles for you. All formal parameters, function declarations and variables are stored there.
Now to answer your actual question: Within the context of a function, its always the fastest possible access to have variables declared with var
. This again is not necesarrily true if we are in the global context. The global object is very huge and its not really fast to access anything within.
If we store things within an object, its still very fast, but not as fast as variables declared by var
. Especially the access times do increase. But nonetheless, we are talking about micro and nanoseconds here (in modern browser implementations). Old’ish browsers, especially IE6+7 have huge performance penalties when accessing object properties.
If you are really interested in stuff like this, I highyl recommend the book ‘High Performance Javascript‘ by Nicholas C. Zakas. He measured lots of different techniques to access and store data in ECMAscript for you.
Again, performance differences for object lookups and variables declared by var
is almost not measureable in modern browsers. Old’ish Browsers like FF3 or IE6 do show a fundamental slow performance for object lookups/access.