Thursday, January 25, 2018

Types of Functions in JavaScript- A Very Easy Explanation

Web designing or UI Development is one of the best industry to join if you love challenges and want to lead a happy life. This industry is one of the top highly paying industry for youth. JavaScript is the key language either you are a web designer or UI developer. So, knowledge of JavaScript matters when you want to make your career here.

A function is a group of reusable code which can be called anywhere in your program. It eliminates the need of writing the same code repeatedly. It helps in writing modular codes. Mainly JavaScript has 2 types of functions:
  1. Built-in functions:
Already defined in the JavaScript language, we invoke them again and again.
Examples: window.alert( ), document.write( ), parseInt( ) etc.
  1. User-defined functions:
Custom functions defined by user.
Below, we will see how to define our own user-defined functions. 
1. Function Definition
Before we use a function, we need to define it.
Syntax:
function functioName(parameter-list)
{
  statements
 }

To define a function in JavaScript, use the function keyword, followed by a unique function name, a list of parameters (that can be empty), and a statement block surrounded by curly braces.
Example:
function sayHi()  
{  
      Var x=10;
            alert(x);  
}

This example above does not have any parameters.

2. Calling a Function
To call a function specify the function name with parenthesis in front of it in the body section. Similarly, a function can be called inside another user defined function too.

Syntax:

<script type="text/javascript">
function functionName( )  
{
 ….code to execute…..
 } </script>

<script type="text/javascript"> functionName(); <script>

Example:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">  
function helloAlert( )
 {
alert("Hello World!");
}  
</script>
</head>
 <body>  
<script type="text/javascript">  
helloAlert();
<script>
</body> </html>

In the above example we have defined a function “helloAlert()”, this function is later called in the body of the code and outputs a pop up that says “Hello world”;
3. Function with Parameters/Arguments
When you call a function, you can pass along some values to it, these values are called parameters or arguments. Parameters are the variables we specify when we define the function. When the function is later called somewhere else in the code, arguments are the values passed as parameters. We can specify multiple parameters, separated by commas (,). The parameters then serve as variables that can be used inside the function.
Syntax:

function functionName( parameter1 , parameter2 . . . parameter n)
{ some code to be executed }

Example:

<script>
function Hello( user )
{ alert( "Hello " + user +”!”); }
</script> <script> welcome( "Rav" ); </script>


In this example, we define a function named Hello( ) that takes in one parameter, named user. When the function is called, we pass the argument "Rav”. The function above when invoked will display the message box "Hello Rav!" on the webpage.
4. Functions with a return Value
Sometimes you want your function to return a value back to where the call was made. This can be done by using return statement. When using return statement, the function returns the specified value. Return is an optional statement.
Syntax:
function returningFunc(parameter) { Result= …. Execute code… return result; }

Example:
<html>  
             <head>
<script type="text/javascript">
function concatStrings(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatStrings (‘raveen’, ‘anand’);
document.write(result );
}
</script>
</head>
Try above example we defined a function that takes two parameters and concatenates them before returning the resultant in the calling program.
5. Nested Functions
JavaScript allows function definitions to be nested within other functions as well. Still there is a restriction that function definitions may not appear within loops or conditionals. These restrictions on function definitions apply only to function declarations with the function statement.
  1. Scope of the nested function is limited to its parent function
  2. The inner functions can access its parent variables but not otherwise.
Syntax:
 
function outerFunction()
      { var a, d, e;
 function innerFunction()
   {  
var f;  
}  
innerFunction ();
 }  
OuterFunction();

Example:

function hypotenuse(a, b) { function square(x)
{
return x*x;
} return Math.sqrt(square(a) + square(b)); } hypotenuse(1,2); In the above example we are calculating the hypotenuse of 2 numbers. Formula for hypotenuse is , here we calculate the square of the numbers in a nested function “square” which tales a number as input and returns its square.
6. Anonymous Functions
anonymous function is a function that is declared without any name. These functions can be assigned to variables when they are created, which gives the same capabilities as using a name within the function head. One common use for anonymous functions is as arguments to other functions.

Example:
var anon = function() { alert('I am anonymous'); } anon();

Differences between creating a named function and an anonymous function :
An anonymous function assigned to a variable only exists and can only be called after the program executes the assignment.

Named functions can be accessed anywhere in a program.

Can change the value of a variable and
assign a different function to it at any point
Not flexible-fixed name
Self-executing anonymous functions or IIFE
Another use for anonymous functions is as self-executing functions. A self-executing anonymous function is a function that executes as soon as it’s created. To turn a normal anonymous function into a self-executing function, you wrap the anonymous function in parentheses and add a set of parentheses and a semicolon after it.

The benefit of using self-executing anonymous functions is that the variables you create inside of them are destroyed when the function exits. In this way, you can avoid conflicts between variable names, and you avoid holding variables in memory after they’re no longer needed.
var myVariable = "I live outside the function."; (function() {
var myVariable = "I live in this anonymous function"; document.write(myVariable);
})();
document.write(myVariable);

In the example above, we have a variable myVariable declared globally. We have an anonymous self-executing function using the same variable name. The output of this is
I live in this anonymous function. I live outside the function”
7. Functions as Closures in JavaScript
A closure is the local variable for a function, kept alive after the function has returned. It is a function having access to the parent scope, even after the parent function has closed. An inner function is defined within an outer function. When the outer function returns a reference to the inner function, the returned reference can still access the local data from the outer function.
function greetVisitor(phrase) {  
var welcome = phrase + "Folks!"; // Local variable
 var sayWelcome = function() {
  alert(welcome);
}
return sayWelcome;
} var personalGreeting = greetVisitor('Hi');
 personalGreeting(); // alerts "Hi Folks!"
 
Conclusion is that functions in JavaScript are must to know as they are the building blocks in it for a web designer. There are many types of functions, you will understand their importance as you will use them in your JavaScript courses. You can learn it separately from any training center or you can join a complete course in web designing from a reputed web designing institute.

No comments:

Post a Comment

Featured Post

ADMEC Multimedia Institute Scholarship Program

The ADMEC Multimedia Institute scholarship program aims to select and trained talented non working female, married woman and non married m...