web training room for online courses
Learn JavaScript, Free JavaScript Tutorial for Beginners, Interactive JavaScript Examples

JavaScript Function Examples

Functions are very useful in any programming language, so it's very important to understand how to write function an call them.

A javascript function is a reusable code block which will be executed only if it is called, Function will always be executed by some event.

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.

function showAlert() {
alert('This is an Alert');
<input type="button" value="Show Alert Message" onclick="showAlert();" />

Example 2: Confirm, Confirm alert is used when you ask user to confirm or not .

function showConfirm() {
var result = confirm("Are you learning javascript");
if (result)
alert('Yes, Learning');
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

function welcomeMessage(firstname) { alert('Welcome ' + firstname + '!');
function callWelcomeMessage() {
var fname = document.getElementById('txtfirstName').value;

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));

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

Name Email Website
How to write Javascript Function, Learn JavaScript Syntax

JavaScript Tutorial