Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q92 How is the "return" reserved word used?

irt.org | Knowledge Base | JavaScript | Misc | Q92 [ previous next ]

Q92 How is the "return" reserved word used?

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?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.