The return statement can be a useful way to create output for a function. The return statement is especially useful if you do not know in which context the function will be used yet.
//An example function that will take a string as input and return
//the first character of the string.
function firstChar (stringIn){
return stringIn.charAt(0);
}
Now to use this function, you need to put it in place of a variable somewhere else in your code:
Using the function result as an argument for another function:
console.log(firstChar("Hello world"));
Console output will be:
> H
The return statement ends the function
If we modify the function in the beginning, we can demonstrate that the return statement ends the function.
function firstChar (stringIn){
console.log("The first action of the first char function");
return stringIn.charAt(0);
console.log("The last action of the first char function");
}
Running this function like so will look like this:
console.log(firstChar("JS"));
Console output:
> The first action of the first char function
> J
It will not print the message after the return statement, as the function has now been ended.
Return statement spanning multiple lines:
In JavaScript, you can normally split up a line of code into many lines for readability purposes or organization. This is valid JavaScript:
var
name = "bob",
age = 18;
When JavaScript sees an incomplete statement like var
it looks to the next line to complete itself. However, if you make the same mistake with the return
statement, you will not get what you expected.
return
"Hi, my name is "+ name + ". " +
"I'm "+ age + " years old.";
This code will return undefined
because return
by itself is a complete statement in Javascript, so it will not look to the next line to complete itself. If you need to split up a return
statement into multiple lines, put a value next to return before you split it up, like so.
return "Hi, my name is " + name + ". " +
"I'm " + age + " years old.";