Start learning free

LESSON 43 OF 671 · FUNCTIONS I

Returning from functions in JavaScript

Lesson

We can pass values into a function with arguments. You can use a return statement to send a value back out of a function.

The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):

function plusThree(num) {
	return num + 3;
}

let answer = plusThree(5);

answer has the value 8.

plusThree takes an argument for num and returns a value equal to num + 3.


No return statement:

In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is undefined.

let sum = 0;

function addToSum(num) {
	sum += num;
}

let returned = addToSum(3);

console.log(sum); // Output: 3
console.log(returned); // Output: undefined

addSum is a function without a return statement. The function will change the global sum variable but the returned value of the function is undefined.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 6
    Ctrl + Enter to check