0

I need to know which is the better way of declaring some local variables. Which is better in terms of practice, performance? Since, local variables declared inside the function gets removed as soon as the function is executed, does declaring as many local variables (eg: a,b in example below) inside various functions compared to declaring only once inside document.ready() makes any difference?

Method 1:

<script type="text/javascript">

$(function() {
    getItem1();
    getItem2();
}

function getItem1() {
    var a = 100;
    var b = 1000;
    //do something with a,b
    return item1;
}

function getItem2(){
    var a = 100;
    var b = 1000;
    //do something with a,b
    return item2;
}

</script>

Method 2:

<script>

$(function() {
    var a = 100;
    var b = 1000;
    getItem1(a,b);
    getItem2(a,b);

}

function getItem1(a,b) {
    //do something with a,b
    return item1;
}

function getItem2(a,b) {
    //do something with a,b
    return item2;
}

</script>
user3399326
  • 863
  • 4
  • 13
  • 24

2 Answers2

0

It's all a matter of what you need, really.

Will you be reusing your functions on multiple instances? Will it be true that if a and b will be supplied on all possible scenarios, the code inside getItem will process the values correctly? If so, then passing the values will be a good choice since you have the free will to pass whatever you want to. If a and b are just constant and will never change at all, then having the values constant would be a great idea as well.

The second choice gives a lot of flexibility and you can change the values anytime you want, this makes the code more 'generic' and 'reusable' - provided you're going to use the same process.

Performance wise, they make a little difference. With the first option allocating a bit more memory since you have to instantiate a and b twice.

Nathan
  • 1,520
  • 1
  • 12
  • 21
0

It's really an idea of why i am using these functions and what are my purposes because it may vary, in Method 1 you are declaring the variable inside a function which those variable will be saved in memory as soon as the function is being executed and they will be deleted when it finish , so if the function contain too many variables and too many lines of code it will not be a good idea if you r looking for performance so it is better using Method 2 ,but if your function is easy and having few lines of code with easy execution method 1 is better of course

Sora
  • 2,465
  • 18
  • 73
  • 146