Hi i am a JavaScript learner at the beginner stage. i am learning about functions now and do not really understand this part of the "return" value. In the book, It explains that the "return" code tells javascript to exit the function and return the value of the_nice_date to whatever variable is waiting for it. (outputs whatever value comes after return) I do not understand what do they mean by return the value to whatever variable is waiting for it. Does it mean that if i want to create a variable for the function as in this case i need to always put this "return" code to it? why? when will i need to use it and in what sort of situation?
var today = getNiceDate(); a return is used in this function to pass the value to the variable today. so you can display it or if you will still need to use it in other process.
Hi, maybe this could better illustrate the meaning: 1. try to add this outside the function - alert(getNiceDate()) - and you'll see the string 2. add '//' (comment) before return line in the function and refresh the page - and you'll see nothing because the alert doesn't have any output or result of the function - return tells that this value I want to get when calling the function, without return, the variable the_nice_date is just used inside the function and you have no way to access it from outside Btw. By using this : var today = getNiceDate(); you would then be able to alert(today) with the same result as alert(getNiceDate())
Does that mean that the return value is always use in the function? What i was also confused about is the "var the_nice_date" needs a return whereas the other var ( such as var the_month = now.getMonth() + 1; ) does not need a return and it fit in nicely in the "var the_nice_date". And both of them is a string as well.
No, it doesn't need to be always there. As you read in your book - "return" code tells javascript to exit the function and return the value of the_nice_date. Sometimes you don't want any return value and function exits generally automatically, when it performs all commands assigned to it. So, it doesn't need to be in every function. And the other thing - as you now know return exits the function, so you need to find a way how to return all three values - year, month, day. That's why you created new variable the_nice_day, that you can use for concatenating all three strings into one, and then return the one value - the_nice_date
Not necessary. A function can do something else beside returning value. like: function redirect() { location.href = 'what.php' } Code (markup): The code above doesn't return anything, it redirects