Home HTML CSS JavaScript React Gamedatum.com
× Home HTML CSS JavaScript React Gamedatum.com

JS Functions


JavaScript Functions

A JavaScript Function is a block of code which allows the user to perform a specific task.

The syntax of a javascript function is this:

function functionName(parameters) {
block of code to be executed
}

When you write your code make sure that everything is inside the curly braces({ }).

The functions can be called multiple times whevever is necessary without the need to re-write the same code for the same functionality making your code more efficient.

This helps with a basic concept in coding called DRY which stands for Do not Repeat Yourself.

When you envoke a function is called: "calling a function" or "call a function"

There are lots of things you can achieve with functions, for example you can call another function from inside a function.

When writing a function make sure that you make a note of what the functionality/purpose of the function is about as it is good practice and helps you and other developers to understand your code much faster.

Example:

               
                
<script>

var x="I'm number ";
var y= 5;
var amount
function myFunction() {
var amount = x + y;
document.getElementById("add").innerText = amount;
}

</script>
                
                
              

In a function you can also pass "parameters".

such as below:

               
                
<div id="function-result"></div>
   <script>
var total = myFunction(6, 2); 
document.getElementById("function-result").innerText = total;

function myFunction(x , y) {
return  x + y;
}

</script>
                
                
              

The output: