×

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 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 Console log Multiple variables

What does console.log() do in JavaScript? The console.log() is a function in JavaScript language. It is used to: Print any message in the console which is visible to the userPrint the values...

3 minutes read.

Javascript Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

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

JavaScript Time Picker Demo

Time Pickers in JavaScript are lightweight and mobile-friendly controls that let the users enter or select date and time values. These values can be from a pop-up calendar or a...

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

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

JavaScript setTimeout()

The setTimeout() method creates a timer that, when it expires, runs a function or provides a piece of code. setTimeout() is an asynchronous function, which means that it will not interrupt...

3 minutes read.

JavaScript moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 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 redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 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 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 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 Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 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 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 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 Image resize before upload

Image resizing can be a quite tedious task, so it is usually done on the server-side. The resized image file is then delivered to the client side. However, sometimes the...

3 minutes read.