aliciousness
aliciousness

Reputation: 1

What is the point of the return in Javascript?

I've recently been learning javascript and came across the return statement or whatever it is. I've watched tutorials on it and I still don't get the point of it. Do I ever need it for anything and can someone please explain in detail what it does? Thanks

Upvotes: 0

Views: 376

Answers (3)

Ian Hazzard
Ian Hazzard

Reputation: 7771

Here's the most common use of the return statement:

document.getElementById("demo").innerHTML = myFunction(5,3); // Call a function
// to set the "demo" element to the value of: 5 * 3

function myFunction(a,b) {
    return a * b;
}
<p id="demo"></p>

Use it to return a value. Your value could be "Yes", "false", "hello world" or "eat dirt." You can then run certain code based on the returned value.

Hope this helps!

Upvotes: 0

user3434588
user3434588

Reputation:

The only point of it is to send a value (string, number, or other values) from your function so that is can be used outside the function. Instead you can use global variables but that takes up more code, so it's a shortcut instead.

jfreind00 above said that you can use it to branch off early but that's what break. Here is the syntax:

function HiThere(something) { if (something === true) { break; } alert("Hi"); }

In this case, if something is true, then exit the function, if not then say hi. Return would be like this:

function HiThere(something) { if (something === true) { return "Value to return: " + something; } alert("Hi"); }

In this case, if something is true, then exit the function and return Value to return: true, if not then say hi but don't return anything back.

Upvotes: 0

jfriend00
jfriend00

Reputation: 707198

The return statement has multiple uses:

1) Return early from your function before the end of the function body. This is often within a branch of the code as in:

function whatever()
    // do some things
    if (err) {
        console.log(err);
        return err;
    }
    // other code here that will not execute if there was an err
}

2) Return a specific value back to the caller as in:

function add(a, b) {
    return a + b;
}

var sum = add(3,4);
console.log(sum);     // will show 7

The return statement in javascript can be used by itself to just exit the current function call and not return a specific value or it can be used to return a specific value.

If no return statement is present in a function, then the function will execute to the end of the function body and will return automatically at the end of the function body.

Upvotes: 1

Related Questions