In a program, we offen need to use same block of code in many different places, in that suitations functions play an important role. In function, we can define code once, and use it as many times as required.
In this section we will discuss User-defined functions.
Below figure contains function keyword, function name, curly brackets, function body including statements and function calling.
Function name should be brief, meaningful, easy to read and in camel case eg: showMessage(), calcPower(), createResult(), etc.
Example 1: function without parameter, without return type.
Example 2: function with parameter, without return type.
Example 3: function without parameter, with return type.
Example 4: function with parameter, with return type.
A variable can be declared inside or outside function. A variable declared inside a function is known as local variable, A variable declared outside a function is known as global variable.
Local variable scope is limited within a function
Global variable scope can be used outside function and can be used inside whole web page.
Example 5: Local variable
function square(){ let n=10; let s=n*n; alert('Square = '+s); // display 100 } square(); //function call alert('Square = '+s); // Error, cannot access outside function
Example 6: Global variable
let s; //global variable function square(){ let n=10; s=n*n; alert('Square = '+s); // display 100 } square(); //function call alert('Square = '+s); // display 100
If we declare a parameterized function and does not pass the argument then error will prompt, but if we declare a function with default value and does not pass any argument then default value will be assigned.
Example 7: Default argument
function power(n, p=2){ let s=Math.pow(n,p); alert('Power = '+s); } power(10,3); //function call with 2 arguments, Output: Power = 1000 power(10); //function call with only 1 argument, Output: Power = 100
There are some points mentioned to write your code that looks good, easy to read and understand. Lets understand coding style which is more prefered.
Ad: