Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q92 How is the "return" reserved word used?

You are here: irt.org | FAQ | JavaScript | Misc | Q92 [ previous next ]

Return is used within functions or statements to return a value to the caller of the function. For example you could use a define the following function:

function test1(text1) {
    document.write('The value of the parameter passed is ' + text1);
}

test1('xyz')

Or, using return as follows:

function test2(text2) {
    return 'The value of the parameter passed is ' + text2;
}

document.write(test2('abc'));

In this example the document.write would display:

The value of the parameter passed is abc

It can be used to return true or false:

function it_is_positive(number) {
    if (number > -1)
        return true;
    else
        return false;
}

if (it_is_positive(-1))
    document.write('Positive');
else
    document.write('Negative');

Another example using is_it_positive:

var string = is_it_postive(123);

Obviously these examples are contrived. But the return keyword is extremely useful at returning variable values of data back from a function, depending on the processing carried out in the function.

The following function is invalid as it does not always return a value:

function invalidFunction(number) {
    if (number == 1)
        return true;

    number = 3;
}

Feedback on 'Q92 How is the "return" reserved word used?'

©2018 Martin Webb