Categories
JavaScript Web development

JavaScript Functions

Functions are one of the fundamental building blocks in JavaScript.

JavaScript Functions
Do you like this gif? Check more gifs in theĀ store.

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when “something” invokes it (calls it).

Example:

<!DOCTYPE html>
<html>
<body>

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

<p id="demo"></p>

<script>
function myFunction(p1, p2) {
  return p1 * p2;
}
document.getElementById("demo").innerHTML = myFunction(5, 4);
</script>

</body>
</html>

Output:

JavaScript Function Syntax

A JavaScript function is defined with the function eyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables – to see varibles rules click here).

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {
}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Return

When JavaScript reaches a return statement, the function will stop executing.

Functions often compute a return value. The return value is “returned” back to the “caller”:

<!DOCTYPE html>
<html>
<body>

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

<p id="demo"></p>

<script>
var x = myFunction(6, 4);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
  return a * b;
}
</script>

</body>
</html>

Output:

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Instead of using a variable to store the return value of a function:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"The temperature is " + toCelsius(77) + " Celsius";

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

</body>
</html>

Output:

Enjoy coding!

Leave a Reply