JavaScript – Functions

A function is a type of procedure or routine, a block of code inside curly braces {} that will be executed when “someone” calls it. Most programming languages come with a prewritten set of functions that are kept in a library. You can also write your own functions to perform specialized tasks. With functions you can write less code and do more!

LOCAL VARIABLES
The variables declared inside a function becomes LOCAL and can only be accessed from within that function.
Local variables are deleted as soon as the function is completed.
You can have local variables with the same name in different functions.

GLOBAL VARIABLES
The variables declared outside a function becomes GLOBAL and they will die when you will close the webpage.

Basic code:

<!DOCTYPE html>
<html>
<head>
<script>
function helloWorld()
{
alert("Hello World!");
}
</script>
</head>

<body>
<button onclick="helloWorld()">Run the function!</button>
</body>
</html>

Syntax:

function functionname()
{
... you want to do ...
}

Arguments: when you call a function, you can pass along some values to it.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to call a function with arguments</p>

<button onclick="myFunction('Harry Potter','Wizard')">Try call Harry</button>
<button onclick="myFunction('Bob','Builder')">Try call Bob</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job); 
}
</script>

</body>
</html>

NOTICE:
1) The result is: “Welcome Harry Potter, the Wizard” if function is called by the first button
1) The result is: “Welcome Bob, the Builder” if function is called by the second button

Syntax:

function myFunction(var1,var2)
{
... you want to do ...
}

Return Value: Using – return – the function will stop executing, and return the specified value.

var myVar=myFunction(); 

function myFunction()
{
var x=10;
return x;
}

1 – When you call

myFunction()

it stops his execution and return a value of 10
2 – The variable – myVar – stores the – return – value of 10
3 – myVar=10;

Below notice:

innerHTML=myFunction();

You can use – return – value without variables:

...
document.getElementById("demo").innerHTML=myFunction();
...

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(a,b)
{
return a*b;
}

document.getElementById("demo").innerHTML=myFunction(4,3);
</script>

</body>
</html>

Return Value with if condition:

function myFunction(a,b)
{
if (a>b)
  {
  return;
  }
x=a+b // calculate x only if a<b
}

My official WebSite >