Functions can be called many times in order to reuse the code which is already written. With functions, you are required to write some code just once and then reuse it as many times as you need.
Syntax for function declaration & definition:
function functionName(parameter1, parameter2, ..., parameterN) { // body code // return value, if required }
A function in JavaScript is declared using the function keyword. This is how the translator comes to know that the definition followed by the function keyword is that of a function. Then you specify the name of the function, which should be a valid identifier. After that, you give parenthesis inside which you specify the parameters which receive values as arguments. All the parameters are separated by comma. Then, you start the curly braces wherein you write the body of the function, which is the code to be executed when the function is invoked. Inside the function, you can optionally return some value.
Syntax for function invocation or function call:
functionName(argument1, argument2, ..., argumentN);
Example:
function applyDiscount() { var cartAmount = 1000; var discount = 100; cartAmount -= discount; console.log(cartAmount); } applyDiscount();
Output:
900
Watch the video given below to revise everything you know about functions.