Functions in javascript

25-05-2018 functions javascript es5 es6 arrow functions named functions Closures Nested Functions Callbacks Arrow functions.

Function nothing but, a group of reusable code which can be called/used anywhere in our application. To avoid code redundancy. Functions are used to divide the block of code to small and manageable methods. 

Javascript have some built-in functions, like alert(message), prompt(message, default) and confirm(question).

Below are some global functions / global methods

  1. decodeURI()
  2. isNaN()
  3. parseInt()
  4. parseFloat()

And below are some String Methods

  1. charAt()
  2. charCodeAt()
  3. concat()
  4. indexOf()
  5. lastIndexOf()

JavaScript allows us to write our own functions as well.
The most common way to define a function in JavaScript is by using the function keyword, followed by a name for the function.

  1. The function name is unique.
  2. After the function name, open and close parentheses.
  3. After parenthesis, open and close curly braces.
  4. Within curly braces, write your lines of code.

If the change the order for initialize and calling steps it will through the error. 

Simple Functions / Named Functions

Basically simple functions are declared in any where in the html page. Steps for declare and calling the simple function is

  1. Initialize the function
  2. Calling the function

Below is the syntax for initialize the simple function in JavaScript.

<script type="text/javascript">
      function Hello() {
         alert("Hello there");
      }
</script>

Calling simple function.

Below code for calling simple functions from script.

<script type="text/javascript">
	// Invoking / Calling the function
Hello();
</script>

Below code for calling simple functions from html onclick event.

<button onclick=”Hello()”></button>

Simple Functions with Return type.

Below is the code for simple functions with return type

<script type="text/javascript">
      function Hello() {
         return true;
      }
</script>

Calling simple return function.

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

The output is  “true”.

We can store returned result like below code.

<script type="text/javascript">
      var returnedResult  = Hello();
</script>

Parameter Functions

Parameter function also similar to simple functions. Below is the code for declaring parameter function. 

<script type="text/javascript">
function myFunction(x, y) {
	var z = x+y;
	console.log(z);
}
</script>

Calling the parameter function from script.

<script type="text/javascript">
      myFunction(2, 3);
</script>

The output is “5”.

Below code for calling simple functions from html onclick event.

<button onclick=”myFunction(5,5)”></button>

The output is “10”.

In the above example myFunction is nothing but function name and x, y are Parameters (or) Arguments. Arguments are object type. The count of calling function parameters and count of called function parameters should be same and order also.

Here is the example for Arguments objects, below the code for getting parameters values from Arguments.

<script type="text/javascript">
function add() {
var addition = 0;
    for (var i = 0; i < arguments.length; i++) {
       addition += arguments[i];
    }
    console.log(addition);
}

add(1, 13, 80, 143);
</script>

The output is “237”.

Parameter Functions with Return type.

 

Below is the example for parameter function with return type.

<script type="text/javascript">
function add(x,y) {
    return x+y;
}
</script>

Calling the parameter function from script.

<script type="text/javascript">
     console.log(add(1, 2));
</script>

Closures / Nested Functions

A function inside function is nothing but Closures or Nested Functions. Here is the example for declaring Closures.

<script type="text/javascript">
function a(){
	function b(){
        }
}
</script>

How to call b function from a function.

<script type="text/javascript">
function a(){
     function b(){
	alert(“called b function”);
     }
     b(); // after calling a function automatically call b function
}
a(); // automatically call a function
</script>

 

  1. While loading page, calling function a, then automatically call function b.
  2. Function b access all parent local variables and methods.
  3. Function a cannot use b local variables.
  4. We cannot call b function directly.

But there is alternate for calling inner function, here is the example for calling b function 

<script>
var a = function(){
  function b(){
    alert('b');
  }
  a.b = b;
}
a();
a.b();
</script>

When we call a() function then only we can call b function.

Self Calling Functions

Self calling function nothing but, calling it self automatically, this type of function are used for calling loading api calls.
Below is the example for self calling function

<script>
(function () {
  // Logic.
   alert(‘Hi’);
}());
</script>

This is also called as Anonymous Functions or Self Invoking Functions

Recursive Functions

Calling it self function is called recursive function. Below is the example for recursive function.
Finding factorial of given number without using for loop

<script>
function factorial(num) {
  if (num <= 0) {
    return 1;
  }else{
    return (num * factorial(num - 1));
  }
};
alert(factorial(5));
</script>

Output is “120”.

Callback Functions

A callback function is a function passed into another function as an argument. Below is the example for callback function

<script>
function displayName(name) {
  alert('Hi ' + name);
}

function askName(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

askName(displayName);
</script>

Here displayName is another function, we are passing function as a parameter.
Callback function are also used to send response of asynchronous api, below example for asynchronous api (AJAX call).

<script>
function getName(callback) {
  $.post('url').done(function(resp){
     callback(name);
  });
}

getName(function(ajaxresp){
  console.log(ajaxresp);
});
</script>

Anonymous Functions

Anonymous function is a function without a name. Anonymous functions are created at runtime. Below is the example for declaring the Anonymous functions. These are looking similar to self calling functions.

<script>
function(){
  alert(‘Hi’);
}
</script>

But we can assign Anonymous functions to variables like below.

<script>
var a = function(){
  alert(‘Hi’);
}
a(); // Calling Anonymous function.
</script>

 

Basically there is small difference between Simple function and Anonymous functions. Simple functions are having function name but Anonymous functions do not have function name. We can assign Anonymous functions to a variable as shown above.

Arrow functions (ES6)

Arrow functions – also called “fat arrow” functions, Arrow functions are from ES6 to latest versions.there are two main benefits of arrow functions,

  1. Shorter Syntax
  2. No binding of this
The normal function syntax like
<script>
function funcName(params) {
   return params + 2;
 }
funcName(2);
// 4
</script>

The arrow function syntax like 

<script>
var funcName = (params) => params + 2
funcName(2);
// 4
</script>

 

 

 

 

 

 

You might also like:

How to insert bulk information into database in single query execution
18-03-2017 insert sql bulk database
How to use http-post request in node js
14-03-2017 http-post module node js
Filter for change Date format (MM-dd-yyyy) in Angular Js
05-03-2017 mm-dd-yyyy date formats angular js
Get random strings from given string In javascript
21-02-2017 javascript random string
Get Unique values from array/object in javascript
19-02-2017 javascript unique remove repeated values from array