×

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the code.

Advantages of JavaScript functions

  1. Code reusability: We call function multiple time to save time as well as coding also.
  2. Less coding: It make our program compressed. We don't write many lines of code each time to perform common task.
Syntax
function functionName(parameter or not)  
{  
statements  
}
Example
<!DOCTYPE html>  
<html>  
<body>  
<script>  
function msg()  
{  
alert("Hello! world");  
}  
</script>  
<input type="button" onclick="msg()" value="click here"/>  
</body>  
</html>
Try Now Output
Hello world! 

Function with arguments

Call function by passing arguments.
<!DOCTYPE html>  
<html>  
<body>  
<script>  
function getcube(number)  
{  
alert(number* number* number);  
}  
</script>  
<form>  
<input type="button" value="click" onclick="getcube(3)"/>  
</form>  
</body>  
</html>
Try Now Output
27
Example
<!DOCTYPE html>  
<html>  
<body>  
<script>  
function getname()  
{  
name=prompt("Enter the Name");  
alert("Welcome Mr/Mrs " + name);  
}  
</script>  
</body>  
<form>  
<input type="button" value="Click" onclick="getname()"/>  
</form>  
</html>
Try Now Function with return value Call function that return value and use it in program.
<!DOCTYPE html>  
<html>  
<body>  
<script>  
function getInfo()  
{  
return "Hello Raj! How are you?";  
}  
</script>  
<script>  
document.write(getInfo());  
</script>  
</body>  
</html>
Try Now Output
Hello Raj! How are you?

The Function() Constructor

A function statement is not only the method to define new function, we can define function dynamically using Function() constructor along with new operator also. Syntax
<script>  
    var variablename = new Function(Arg1, Arg2...,  "Function Body" );   
</script>
Example
<!DOCTYPE html>  
<html>  
<head>  
<script>  
var func = new Function("a", "b", "return a+b;");  
function secondFunction(){  
var result;  
result = func(50,50);  
document.write ( result );  
}  
</script>  
</head>  
<body>  
<p>Click button to call the function</p>  
<form>  
<input type="button" onclick="secondFunction()" value="Call Function">  
</form>  
<p>Use different parameters inside the function and try yourself...</p>  
</body>  
</html>
Try Now

Function Literals

JavaScript 1.2 introduces the concept of function literals which is another method to define functions. It is an expression that defines an unnamed function. The syntax for function literal is like function statement, except it is used as an expression rather than a statement and no function name is required. Syntax
<script>  
var variablename = function (Argument List){  
          Function Body  
};    
</script>
Example
<!DOCTYPE html>  
<html>  
<head>  
<script>  
var func = function(a,b){ return a+b };  
function secondFunction(){  
var result;  
result = func(10,20);  
document.write ( result );  
}  
</script>  
</head>  
<body>  
<p>Click the button to call the function</p>  
<form>  
<input type="button" onclick="secondFunction()" value="Call Function">  
</form>  
<p>Use different parameters inside the function and try yourself...</p>  
</body>  
</html>
Try Now

Related Topics

Javascript Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

1 minute read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.

Javascript Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

Javascript Find Object In Array

What is find() method? It returns the value of the first element in the given array that fulfils the given testing function. However, if no values from the array are able...

3 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

Javascript Math

Math is build-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. Syntax varpi_val = Math.PI; varsin_val = Math.sin(30); Examples Math.pow() Math.pow(x,y) returns the value of x to the power...

2 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

3 minutes read.

Javascript Print

JavaScript help's the functionality using the print function of window object. In JavaScript print function window.print() print the current web page when it executed. We can call function directly using onclick...

1 minute read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Javascript input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Minify JavaScript

What do you mean by the term ‘Minification’? The technique of minification reduces the amount of code and markup in your websites and scripting files. It's one of the most used...

4 minutes read.

Javascript If Else

Introduction The if-else statement is an important control structure for decision-making in code based on some conditions. It gives programmers the ability to add decision-making functionality into their programs. Using if-else,...

6 minutes read.

JavaScript setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 minutes read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

2 minutes read.

Javascript Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.