/    /  Javascript-Functions

Javascript-Functions

 

This function is similar to most of the scripting and programming languages.

In JavaScript function is a block of code, give it a name. Then executes it multiple times as you want.

A JavaScript function can be using the function keyword(function()).

 

Syntax:

 

//defining a function
function <function-name>()
{
  // code to be executed
};

//calling a function
<function-name>();

 

Advantage of JavaScript function:

 

  • Code reusability: We can call a function many times so it saves coding.
  • Less coding: It makes our program compact. We don’t need to write several lines of code every time to perform a common task.

 

Example:

 

<html>
<body>
<script> 
function msg(){ 
alert("hello! this is message"); 
} 
</script> 
<input type="button" onclick="msg()" value="call function"/> 
</body>
</html>

 

OUTPUT:

 

Function Arguments:

 

call function by passing arguments.

 

Example:

 

<html>
<body>
<script> 
function getcube(number){ 
alert(number*number*number); 
} 
</script> 
<form> 
<input type="button" value="click" onclick="getcube(6)"/> 
</form> 
</body>
</html>

 

OUTPUT:

 

216

 

Function with Return Value:

 

Example:

 

<html>
<body>
<script> 
function getInfo(){ 
return "hello I2tutorials! good?"; 
} 
</script> 
<script> 
document.write(getInfo()); 
</script> 
</body>
</html>

 

OUTPUT:

 

hello I2tutorials! good?

 

JavaScript Function Object:

 

In JavaScript, the purpose of the Function constructor is to create a new Function object. It executes the code globally. if you call the function “constructor” directly, a function is created dynamically but in an unsecured way.

 

Syntax:

 

new Function ([arg1[, arg2[, ....argn]],] functionBody)

 

Parameter:

 

arg1, arg2, …., argn – It represents the argument used by the function.

functionBody – It represents the function definition.

 

JavaScript Function Methods:

 

apply()             Call a function to define this value and a single array of arguments.

bind()               Create a new function.

call()                Call a function to define this value and an argument list.

toString()         Result in a form of a string.

 

JavaScript Function Object Examples:

 

display the sum of given numbers.

 

<!DOCTYPE html>
<html>
<body>

<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>

</body>
</html>

 

OUTPUT:

 

7

 

display the power of provided value:

 

<!DOCTYPE html>
<html>
<body>

<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,11));
</script>

</body>
</html>

 

OUTPUT:

 

2048