JS Functions

JavaScript Functions

JavaScript Functions

  • A JavaScript function is a section of code that perform a specific task when called. Calling a function is achieved by its name.

Syntax:

function function_name() 
  {
    function code
  }

Example:

<html>
<head>
<script>
function helloFunction()
{
alert("Hello people!");
}
</script>
</head>
<body>
<button onclick="helloFunction()">Press button</button>
</body>
</html>

Calling the Function:

<script type="text/javascript">
<!--
helloFunction();
//-->
</script>

Function with Parameters:

<script type="text/javascript">
<!--
function cityFunction(city, code)
{
   alert(city + " city code is: " + code);
}
//-->
</script>

Calling the Function with Parameters:

<script type="text/javascript">
<!--
cityFunction('London', 5 );
//-->
</script>

Function with a Return value:

<script type="text/javascript">
<!--
function fullname(firstname, lastname)
{
   var name;      
   name = firstname + lastname;
   return  name;
}
//-->
</script>

Calling the Function with Return:

<script type="text/javascript">
<!--
   var thename = fullname('Tom', 'Joe');
   alert(thename );
//-->
</script>