Using the Return Statement
suggest changeThe 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:
const
name = "bob",
age = 18;
When JavaScript sees an incomplete statement such as the const declaration above, it continues on the next line. return followed by a newline is already complete. These fragments also need to be inside a function, and they use name and age from the declaration above. A newline after return inserts a semicolon:
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.";