Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

How to write Javascript Function

Functions are very useful in any programming language, so it's very important to understand how to write function an call them.
A function is a reusable code block which will be executed only if it is called.

How to write a Function in JavaScript

Use the keyword function followed by function name.
write open and close parentheses function name()
After parenthesis there are curly braces open and close {}, inside curly braces you write your codes
function functionName()
{
// here you write code
}

Three points you need to understand
  • How to write function
  • How to pass arguments
  • How to return value

Example 1 : Alert, We often see alert message in many web sites when we fill up some form, we get alert for many reason, if any field is not filled up or with wrong data etc. So this is how we can show alert message using javascript.
<script>
function showAlert()
{
alert('This is an Alert');
}
</script>

<input type="button" value="Show Alert Message" onclick="showAlert();" />


Example 2: Confirm, Confirm alert is used when you ask user to confirm or not .
<script>
function showConfirm() {
var result = confirm("Are you learning javascript");
if (result)
alert('Yes, Learning');
else
alert('Not Learning');
}
</script>

<input type="button" value="Please Confirm" onclick="showConfirm();" />

Javascript Function with Arguments Example

Example 3: Pass Parameters, Now we learn how to pass parameter in Javascript function
Type you firstname
<script>
function welcomeMessage(firstname) {
alert('Welcome ' + firstname + '!');
}

function callWelcomeMessage() {
var fname = document.getElementById('txtfirstName').value;
welcomeMessage(fname);
}
</script>
In above example you also can see how to call a javascript function from another function

How to return value from Javascript Function

Here we have written two functions, the first function Calculate do some calculation based on input parameters and return some value. The second function we have written just to call the function and display the result .
<script>
function Calculate(arg1, arg2) {
var _diff = eval(arg1) - eval(arg2);
return eval(_diff * 10);
}

function DisplayMessage() {
window.alert(Calculate(10, 5));
}
</script>

Javascript Local variables

A variable declared inside a function is only accessible inside that function, is known as local variables.
If you declare a variable outside function that can be accessible in some other function also.
<script>
var bgcolor = "white";
function functionName() {
var fcolor = "red"; // this is local variable
} </script>

 
How to write Javascript Function

JavaScript Tutorial

Group Training