JavaScript Built-in Functions

Function

  • Function is a reusable code-block that will be executed whenever it is called.
  • Function is a great time saver.
  • It is used for performing repetitive tasks where you can call the same function multiple times to get the same effect.
  • It allows code reusability.
  • JavaScript provides number of built-in functions.

Common Built-in Functions

FunctionsDescription
isNan()Returns true, if the object is Not a Number.
Returns false, if the object is a number.
parseFloat (string)If the string begins with a number, the function reads through the string until it finds the end of the number; cuts off the remainder of the string and returns the result.
If the string does not begin with a number, the function returns NaN.
parseInt (string)If the string begins with an integer, the function reads through the string until it finds the end of the integer, cuts off the remainder of the string and returns the result.
If the string does not begin with an integer, the function returns NaN (Not a Number).
String (object)Converts the object into a string.
eval()Returns the result of evaluating an arithmetic expression.

User-defined Functions

  • User-defined function means you can create a function for your own use. You can create yourself according to your need.
  • In JavaScript, these functions are written in between the <HEAD> tag of the HTML page.
Syntax:
function function_name()
{
     //Code;
}

Example : Function Declaration

function add()    
{
     var a, b;
     var sum = 0;
     sum = a + b;
     document.write(“Addition : ”+sum);
}

How is a function executed on an event in JavaScript?

<input type= “button” onClick= “add()” value= “buttonvalue”>

  • onClick – Event Handler
  • add() – Function name

Example : Simple Program on User-defined Function

<html>
<body>
     <script type="text/javascript">
     function add()          // Function Declaration
     {
          var a = 2,b = 3;
          var sum = 0;
          sum = a+b;
          document.write("<b>Addition: </b>"+sum);
     }
     </script>
     <p> Click the Button</p>
     <input type="button" onClick="add()" value="Click">          //add() - Calling Function
</body>
</html>


Output:
user defined function add
Addition: 5