Bookmark and Share

functons

javascript_logo.png





Functions

A JavaScript function is a block of code designed to perform a particular task which is executed when invoked (called).

Here is the basic function in JavaScript:

<!DOCTYPE html>
<html>
<body>

<p>This example calls a function which performs a multiplication, and returns the result:</p>

<p id="multiply"></p>

<script>
function m(x, y) {
    return x * y;
}
document.getElementById("multiply").innerHTML = m(9, 5);
</script>

</body>
</html>

The following code convert Fahrenheit to Celsius after getting the input:

<!DOCTYPE html>
<html>
<body>

<p id="function_demo"></p>

<script>
function convert() {
  var f = document.getElementsByName('degree_in_F')[0].value;
  document.getElementById("function_demo").innerHTML = "The temperature is " + toCelsius(f).toFixed(1) + " Celsius.";	
}

function toCelsius(fahrenheit) {
  return (5/9) * (fahrenheit-32);
} 
</script>

<form name="test">
<h2>Enter degree and press the button. <br>
Please try this a few times.</h2>
<p>Enter degree in Fahrenheit: <input type="number" name="degree_in_F"><br><br>
<input type="button" value="Convert" onClick="convert()">
</p>
</form>

</body>
</html>

Note that we used document.getElementsByName() to get the user input and the toFixed(1) truncates after the first decimals.





Anonymous Functions

A function without a name is an anonymous function.

Functions stored in variables do not need function names. They are always invoked (called) using the variable name.

<!DOCTYPE html>
<html>
<body>

<p>This example calls a function which performs a multiplication, and returns the result:</p>

<p id="multiply"></p>

<script>
var fObj = function (x, y) {
    return x * y;
}
document.getElementById("multiply").innerHTML = fObj(9,5);
</script>

</body>
</html>




Anonymous Self-Invoking Functions

Function expressions can be made "self-invoking".

A self-invoking expression is invoked (started) automatically, without being called.

Function expressions will execute automatically if the expression is followed by ().

(f(){})();

Here is the example:

(f(){
   var x = "Self invoking function"
})();