Need help with "return" in JavaScript Functions


#1

So, i get stuck into "return" exercise on JavaScript. I don't have any idea how it works and when/where i should use it. Can anyone help me, please?


#2

It's hard to explain exactly what return does. I personally know that it can be confusing at first.
Some of the basic things you need to know is that:

  • return can only be used in a function.
    This means that you can't use the word return if it's not inside of a function, and if you try, you'll get an error.

  • return doesn't physically log anything to the console.
    Meaning, if you return something, it won't show up, you have to either console.log() the function call, or set it equal to a variable or something. You'll see this more later.

  • return ends a function. Once a return command is reached in the function, the computer will stop reading the function, and move onto the rest of the code.

You want to use the word return at the end of a function, or in some kind of if/else statement. I can't give you a very specific example, because I'm not very good at that, but as you progress and read other people's posts as well as complete the lessons, you'll realize where it's used.

Here is a resource from Stack Overflow's JavaScript documentation that is titled Using the Return Statement.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.