By default, functions return the value undefined. If you want the function to return some other value, you need to have a return statement.
You may also use a return statement to halt execution of the function based on some logic, again returning a value that has some meaning or just undefined.
In the first example in the OP, the function is called and the return value is not used for anything, so it doesn't matter what the return value is and a return statement isn't necessary.
In another scenario, the return value might be important, e.g. a function that generates an integer random number between 0 and 10:
function getRandomInteger(){
return Math.floor(Math.random() * 11);
}
function showRandomNumber() {
document.getElementById('s0').textContent = getRandomInteger();
}
<button onclick="showRandomNumber()">Show random number</button>
<span id="s0"></span>
In the above, the getRandomInteger function needs to return a specific value, so it uses a return statement. The showRandomNumber function just displays the random number, so it doesn't need a return statement as the caller (the listener on the button) doesn't care what the return value is.
sumvariable is declared in a scope such that it is visible both inside the function and outside where the function is called. That is not always the situation, however.returnhow would you useparseInt, for example? Which would be the global variable that would hold the result of this function? What aboutparseFloat()orisNaN(), etc? Would each have its own result variable that you have to remember? Would there be a single result variable? What about the array methods -arr.map().filter().reduce()would be impossible to do without return values.but I can't see a reason why I should use oneYou will see a reason when it comes time to need a reason. Coding is pretty much like that,.. I remember lots of people not seeing any reason for Promises, until the day they started using them.. :)