Learn about JavaScript return statement: So far we have been giving our functions pieces of information in arguments. We can also make our functions give us pieces of information back as values.

When a function gives back a piece of information, we say it has returned the information. To make a function return a piece of information, we have to use a return statement inside the function.

The value in the return statement can be text, numbers or a variable, and it becomes the value of the function. Let’s take a look at how we can use a return statement to give us a piece of text:

<script>
 function getName() {
 return "Bob";
 }
 var userName = getName();
 alert(userName);
</script>

In this example, we’ve created a function called getName.

We want our function to give us Bob’s name as a value, so we’ve used a return statement and set Bob’s name as the value.

We’ve then stored the function name as the variable value.

When the alert pops up, it will pop up with the value of the return.

Functions will often perform an action and return the result to the rest of your code.

FUNCTIONS AND ARGUMENTS

Let’s have a go at grouping together statements and creating a function.

We should also try out the return statement as it will be very useful when we create our password for Bob.

1) Open up your text-editing program.

Create a new HTML file called functions.html.

Type this code into your new file:

<!DOCTYPE html>
<html>
<head>
 <title>Functions</title>
</head>
<body>
 <script>
 </script>
</body>
</html>

2) Inside your < script > block create a function called checkAccess that will pop up an alert
when you call it.

Your code will look like this:

<script>
 function checkAccess() {
 alert("Restricted access!");
 }
 checkAccess();
</script>

3) Save your HTML file and open it in your browser. An alert will pop up.

4) Now change your checkAccess function so that it contains a return statement.

Store the name of your function in a variable.

Then make an alert pop up to show the value of your variable:

<script>
 function checkAccess() {
 return "Expedition team only!";
 }
 var webPage = checkAccess();
 alert(webPage);
</script>