Course

Function Return

Loading...

In this lesson, you'll learn about the return statement in JavaScript functions, which is crucial for understanding how functions output values and control flow.

Return Statement in Functions

Every function in JavaScript returns unless otherwise specified. That means if we don't explicitly specify what we want our function to return , it will always return .

Let's create a function called . It will take in one parameter, called , and return that number multiplied by two. Don't worry about arrow function syntax too much; we'll cover it in greater detail in the next lesson! 😊

Here's a simple function that returns the sum of numbers and :

function add(a, b) {
   return a + b;
}

This function will return the sum of and . We can then invoke the function and save the to a variable:

const sum = add(2, 2);

When we log out our value, we get :

console.log(sum); // 4

Awesome! The statement not only returns values from a function but also assigns them to whatever called the function!

Immediate Function Termination

Another important rule of the statement is that it stops function execution immediately.

Consider this example where we have two statements in our function:

function test() {
  return true;
  return false;
}

test(); // true

The first statement immediately stops execution of our function and causes it to return . The code on line three, ; is never executed.

We can also test it by adding some console logs:

function test() {
  console.log(1);
  return true;
  console.log(2);
  return false;
  console.log(3);
}

test(); // true

As you can see, we only get the console log with the value of . As soon as the function returns something, it doesn't care about anything else. It's done its job, and now other JavaScript code can be run.

In the next lesson, we're going to explore , the modern way of writing JavaScript functions.

Loading...

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Arrow Functions