JavaScript Functions
A function is an independent reusable block of code that performs certain operations on variables and expression to fullfill a task.
function is used for reusebility of code.
Declaring a function
Function function_name(){
body of the function
}
- A function is Declare using function keyword
- The basic rules of naming a function are similar to naming a variable.
- The body of function is written within {}
Example-
<html><body>
<script>
function add()
{
var i,j;
i=parseInt(prompt("Enter a no:"));
j=parseInt(prompt("Enter a no:"));
document.write("res=",i+j);
}
add();//--------------------------------------->Function calling
</script>
</body>
</html>
Nesting with in function
<html><body>
<script>
function add()
{
var i,j;
i=parseInt(prompt("Enter a no:"));
j=parseInt(prompt("Enter a no:"));
document.write("res=",i+j);
}
function sub()
{
add();
var i,j;
i=parseInt(prompt("Enter a no:"));
j=parseInt(prompt("Enter a no:"));
document.write("<br>res=",i-j);
}
sub();
</script>
</body>
</html>
function with parameter
A parameter is a value that is passed when declaring a function.
Declaring parameterized function
Function function_name(name){
body of the function
}
function_name(name);
<html>
<body>
<script>
function add(i,j)
{
var i,j;
document.write("res=",i+j);
}
i=parseInt(prompt("Enter a no:"));
j=parseInt(prompt("Enter a no:"));
add(i,j);
</script>
</body>
</html>
function with return value
<html><body>
<script>
function add(i,j)
{
var i,j;
return i+j;
}
i=parseInt(prompt("Enter a no:"));
j=parseInt(prompt("Enter a no:"));
document.write(add(i,j));
</script>
</body>
</html>