Functions in JavaScript
Functions in greater detail to see how functions are implemented in JavaScript.
The illustration gives an overview of how the program flow would look for a function. Let’s list the properties of a function.
Function features
A function has the following properties:
-
A list of arguments which can be anything and is optional. This is the input to the function.
-
A program block is executed on the invocation of the function.
-
An output that is returned after the function finishes executing using a return statement.
With these features in mind, let’s learn the corresponding JavaScript syntax.
Basic function syntax and semantic
We know a function can have an input, a program block where all the instructions that would be executed reside, and an output that is returned by the function. Below is an outline of a function in JavaScript.
Here, the function starts with a function
token, then the name of the function. This is followed by arguments in parentheses, and concludes with a set of instructions encapsulated within the brackets including a return statement which uses the return
token within the set of instructions.
Write a small function that returns the sum of two numbers passed as arguments.
// Define function that takes the sum of two numbersfunction sum(a , b){console.log('Taking sum in the function'); // print to see function executevar ans = a + b; // assign sum of a and b to ansreturn ans; // return ans as output}
In the above code, we wrote a basic function that has two arguments, a
and b
, written in the parenthesis and ...