JavaScript Define & Call Functions with Example
What is Function in JavaScript?
Functions are very important and useful in any programming language as they make the code reusable A function is a block of code which will be executed only if it is called. If you have a few lines of code that needs to be used several times, you can create a function including the repeating lines of code and then call the function wherever you want.
How to Create a Function in JavaScript
- Use the keyword function followed by the name of the function.
- After the function name, open and close parentheses.
- After parenthesis, open and close curly braces.
- Within curly braces, write your lines of code.
Syntax:
function functionname()
{
lines of code to be executed
}
Try this yourself:
<html>
<head>
<title>Functions!!!</title>
<script type="text/javascript">
function myFunction()
{
document.write("This is a simple function.<br />");
}
myFunction();
</script>
</head>
<body>
</body>
</html>
Function with Arguments
You can create functions with arguments as well. Arguments should be specified within parenthesis
Syntax:
function functionname(arg1, arg2)
{
lines of code to be executed
}
Try this yourself:
<html>
<head>
<script type="text/javascript">
var count = 0;
function countVowels(name)
{
for (var i=0;i<name.length;i++)
{
if(name[i] == "a" || name[i] == "e" || name[i] == "i" || name[i] == "o" || name[i] == "u")
count = count + 1;
}
document.write("Hello " + name + "!!! Your name has " + count + " vowels.");
}
var myName = prompt("Please enter your name");
countVowels(myName);
</script>
</head>
<body>
</body>
</html>
JavaScript Return Value
You can also create JS functions that return values. Inside the function, you need to use the keyword return followed by the value to be returned.
Syntax:
function functionname(arg1, arg2)
{
lines of code to be executed
return val1;
}
Try this yourself:
<html>
<head>
<script type="text/javascript">
function returnSum(first, second)
{
var sum = first + second;
return sum;
}
var firstNo = 78;
var secondNo = 22;
document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));
</script>
</head>
<body>
</body>
</html>
