×

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

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 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 Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 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.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

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...

3 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

Javascript Object

An object is an entity having state and behavior. JavaScript is an object oriented scripting language. JavaScript is template based not class based but we can create object directly. Syntax to...

2 minutes read.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 minutes read.

JavaScript p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 minutes 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 Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

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 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 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 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 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 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.