In JavaScript, a function can return a value using the return
keyword. When a return statement is executed, the function stops executing and the value of the return statement is returned to the calling code. For example:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
function add(a, b) { return a + b; } let result = add(2, 3); // result is set to 5
[/dm_code_snippet]
In this example, the function add()
takes in two parameters, a
and b
, and returns their sum. The calling code assigns the returned value of the function to the variable result
.
It’s also possible to not return any value in a function, in this case the function return undefined
by default.
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
function noReturn() { console.log("Hello World"); } console.log(noReturn()); // "Hello World" and undefined
[/dm_code_snippet]
It’s important to note that once a return statement is executed, the function stops executing and no further code within the function will be executed.
Here are a few more details about using the return
keyword in JavaScript:
- A function can have multiple return statements, but execution will only reach one of them depending on the flow of the code. For example, if a function has multiple
if-else
statements and each branch has a different return statement, only the return statement in the branch that gets executed will be returned. - The
return
keyword can be used to return any type of data, including numbers, strings, booleans, objects, and arrays. - Functions can also return other functions, or even return themselves (recursive functions).
- When a function is called and its return value is not used or assigned to a variable, the returned value is effectively discarded. For example, in the following code, the returned value of the
add()
function is not used, so it doesn’t affect the output:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
function add(a, b) { return a + b; } console.log("The result is not used"); add(2, 3);
[/dm_code_snippet]
- A function can return a promise, which can be used to handle asynchronous operations.
- A return statement with no value, or with no expression after the return keyword, will return
undefined
.