How to Return a Value using Javascript Functions

Guest Posts Paolo Nikko Nuñal

One of the most common problems that people tend to forget when dealing with functions in JavaScript is returning two values. In one of our previous articles we manage to call a function and process some things once it is invoked. This time around, we are going to learn how to create functions and let them return a value. This is pretty easy and all you have to do is use the "return" reserved word to do it.

Code


<script>
     var num1 = 5;
     var num2 = 3;
     var total = 0;
     addNumber(num1,num2);

     alert(total);
     function addNumber(num1, num2){
         total = num1 + num2;
         return total;   
     }
</script>


First of all, we have initialize the variables, num1, num2 and total with 5, 3, and 0 respectively. After which we called the function addNumber() that passes the two variables . In the addNumber() function, it then adds the two variables and we return the added value using the reserved word "total". After which, it displays the total value.

Another example is stated below.

<script>
     var num1 = 5;
     var num2 = 3;

     var total = addNumber(num1,num2);
     var total1 = minusNumber(num1,num2);
     alert("Total of Added"+ total + "Deducted value" + total1);
     function addNumber(num1, num2){
         return x= num1 + num2;   
     }
     function minusNumber(num1,num2){
         return x = num1 - num2;     
}
</script>


Functions are a great way in making your code much simpler and shorter. It also avoids redundancy. Make sure to use functions if possible.