0

I'm learning Javascript and am told setting a variable equal to a function is done all the time. I'm trying to figure out why. Below is sample code that suggests there is no advantage. What am I missing?

<script type="text/javascript">

         var  addVar =  function() {
            var myTemp = 0;

            for(i=0; i< arguments.length;i++){
               myTemp+=arguments[i];
            }
            return myTemp;
         }

         function addFunc() {
            var myTemp = 0;

            for(i=0; i< arguments.length;i++){
               myTemp+=arguments[i];
            }
            return myTemp;
         }

         function addTwo(first,second){
            return first+second;
         }

         alert( addTwo(addVar(1,2,3),addVar(1,2,3)) );
         alert( addTwo(addFunc(1,2,3),addFunc(1,2,3)) );


</script>
DCR
  • 10,658
  • 7
  • 38
  • 86
  • 1
    In this case, there is no advantage. If you need to change the function dynamically, then you need a variable. – Raymond Chen Dec 13 '15 at 15:53
  • could you explain what you mean by change function dynamically? I thought they were immutable – DCR Dec 13 '15 at 16:04
  • Let's suppose you have an async function. When it ends, how do you specify what do? With a callback. And how do you explain to the async function what is a "callback"? You simply put a function in a variable and pass it. Advantage: if you have multiple async functions and you want all of them to do the same thing when they end, you don't have to write the callback every time. – Saturnix Dec 13 '15 at 16:11
  • great answer, thanks – DCR Dec 13 '15 at 16:20
  • @DCR Maybe later on in the program, you want `addVar` to do something different. You can change the `addVar` variable to hold a different function. – Raymond Chen Dec 13 '15 at 20:17

0 Answers0