function as type

Description

Javascript functions are instances of the Function type with properties and methods.

Function names are pointers to function objects.

function expression.

Functions are typically defined using function-declaration syntax as follows:


function sum (num1, num2) {
   return num1 + num2;
}

We may also define it using a function expression.


var sum = function(num1, num2){
   return num1 + num2;
};

There is a semicolon after the end of the function.

function name

It's possible to have multiple names for a single function.


function sum(num1, num2){/*from  w  ww.  j  a  va 2 s .c  o  m*/
   return num1 + num2;
}
console.log(sum(10,10));    //20

var anotherSum = sum;
console.log(anotherSum(10,10));  //20

sum = null;
console.log(anotherSum(10,10));  //20

The code above generates the following result.

No Overloading

There is no overloading in Javascript function as shows in the following code.


function addSomeNumber(num){
   return num + 100;
}
function addSomeNumber(num) {
   return num + 200;
}
var result = addSomeNumber(100);    //300

In this example, declaring two functions with the same name results in the last function overwriting the previous one.

Its equivalent form is:


var addSomeNumber = function (num){
   return num + 100;
};

addSomeNumber = function (num) {
   return num + 200;
};
var result = addSomeNumber(100);    //300




















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions