Skip to content
Home » Use of local variables vs function variables

Use of local variables vs function variables

If variables are used repeatedly in a code block then its better to execute that code block in a function as much as possible to take advantage of the better performance of local function variables instead of executing that code block without function.

Global variables stay in a highly-populated namespace.
They are stored along with many other user-defined quantities and JavaScript variables.

Browser distinguishes between global variables and properties of objects that are in the current context.

In below code, variable c is used repeatedly in for loop.
So run below in your browser console and see that first for loop without function takes more time than the second for loop executed within function.

time1 = new Date();

var c;
for (c = 0; c < 2000000; c++);

time2 = new Date();

function count() {
    var c;

    for (c = 0; c < 2000000; c++);
}

count();
time3 = new Date();

console.log('Without local variables = ', time2 - time1);
console.log('With local variables = ', time3 - time2);

 

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Shares
Tweet
Pin
Share
Share
Share