Practical No-4.
Develop javascript to implement functions
Objective
Develop javascript to implement function
Resource Used
- Computer with a text editor (e.g., Notepad++)
- Web browser (e.g., Chrome, Firefox)
Theory
Function
JavaScript functions are used to perform operations. We can call
JavaScript function many times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need
to write many lines of code each time to perform a common
task.
JavaScript Function Syntax
function function_Name([arg1, arg2, ...argN])
{
//code to be executed
}
JavaScript Functions can have 0 or more arguments.
Example
<html>
<body>
<script>
function msg()
{
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
JavaScript Function Arguments
We can call function by passing arguments. Let’s see the example of function that has
one argument.
Function with Return Value
We can call function that returns a value and use it in our program.
JavaScript Function Object
In JavaScript, the purpose of Function constructor is to create a new
Function object. It executes the code globally. However, if we call
the 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 function.
functionBody - It represents the function definition.
<!DOCTYPE html>
<html>
<body>
<script>
var add=new Function("num1","num2","return
num1+num2");
document.writeln(add(2,5));
</script>
</body>
</html>
Program :
1) JavaScript Function Arguments
<!DOCTYPE html>
<html>
<body>
<script>
function getcube(number) {
alert(number * number * number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
2)Function with Return Value
<html>
<body>
<script>
function getInfo() {
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
Output :
Conclusion