Return Statement
There are some situations when we want to return some values from a function after performing some operations. In such cases, we can make use of the return statement in JavaScript. This is an optional statement and most of the time the last statement in a JavaScript function. Look at our first example with the function named as calcAddition. This function is calculating two numbers and then returns the result.
Syntax: The most basic syntax for using the return statement is:
return value;
The return statement begins with the keyword return separated by the value which we want to return from it. We can use an expression also instead of directly returning the value.
Functions:
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
Functions in JavaScript
A JavaScript function is a block of code designed to perform a particular task. It encapsulates a set of instructions that can be reused throughout a program. Functions can take parameters, execute statements, and return values, enabling code organization, modularity, and reusability in JavaScript programming.
A JavaScript function is executed when “something” invokes it (calls it).
Example: A basic javascript function, here we create a function that divides the 1st element by the second element.
function myFunction(g1, g2) {
return g1 / g2;
}
const value = myFunction(8, 2); // Calling the function
console.log(value);
Output
4
Output:
4
You must already have seen some commonly used functions in JavaScript like alert(), which is a built-in function in JavaScript. But JavaScript allows us to create user-defined functions also. We can create functions in JavaScript using the keyword `function`.
Syntax: The basic syntax to create a function in JavaScript is shown below.
function functionName(Parameter1, Parameter2, ...)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function, separated by the name of the function and parameters within parenthesis. The part of the function inside the curly braces {} is the body of the function.
In javascript, functions can be used in the same way as variables for assignments, or calculations.