JavaScript Function


A function is a reusable block of code that is event-driven or executed when it is called.

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test example</title>
<script>
    function myFunction()
    {
         alert("Hello World!");
    }
</script>
</head>
 
<body>
    <button onclick="myFunction()">Click me</button>
</body>
</html>

 Try It! 


JavaScript Function Syntax

A function is a code block wrapped in curly braces, and the keyword function is used before:

function functionname ()
{
    // executable codes
}

When the function is called, the code inside the function will be executed.

The function can be called directly when an event occurs (for example, when the user clicks a button), and it can be called from any location by JavaScript.

lampJavaScript is case sensitive. The keyword function must be lowercase, and the function must be called in the same case as the function name.

Calling A Function with Parameters

When calling a function, you can pass values to it, and these values are called parameters.

These parameters can be used in functions.

You can send as many parameters as you want, separated by commas (,):

myFunction(argument1, argument2)

When you declare a function, please declare the parameters as variables:

function myFunction( var1 , var2 )
{
    code
}

Variables and parameters must appear in a consistent order. The first variable is the given value of the first parameter passed, and so on.

Example

<p>Click this button to call a function with parameters. </p>
<button onclick="myFunction('Harry Potter','Wizard')">Click here</button>
<script>
    function myFunction(name,job){
         alert("Welcome "+ name + ", the" + job);
    }
</script>

 Try It! 

The above function will prompt "Welcome Harry Potter, the Wizard" when the button is clicked.

The function is very flexible. You can call the function with different parameters, which will give different messages:

Example

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

 Try It! 

Depending on the different buttons you click, the above example will prompt "Welcome Harry Potter, the Wizard" or "Welcome Bob, the Builder".


Functions with Return Values

Sometimes, we want the function to return the value to the place where it was called.

This can be achieved by using the return statement.

When using the return statement, the function will stop execution and return the specified value.

grammar

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

The above function will return the value 5.

Note: The entire JavaScript does not stop executing, it is just a function. JavaScript will continue to execute the code from where the function was called.

The function call will be replaced by the return value:

var myVar=myFunction();

The value of the myVar variable is 5, which is the value returned by the function "myFunction()".

Even if you don't save it as a variable, you can still use the return value:

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

The innerHTML of the "demo" element will become 5, which is the value returned by the function "myFunction()".

You can base the return value on the parameters passed to the function:

Example

Calculate the product of two numbers and return the result:

function myFunction(a,b)
{
     return a*b;
}
 
document.getElementById("demo").innerHTML=myFunction(4,3);

The innerHTML of the "demo" element will be: 12

 Try It! 

You can also use the return statement when you only want to exit the function. The return value is optional:

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

 If a is greater than b, the above code will exit the function and will not calculate the sum of a and b.


Local JavaScript Variables

The variable declared inside the JavaScript function (using var) is a local variable, so it can only be accessed inside the function. (The scope of this variable is local).

You can use local variables with the same name in different functions, because only the function that declares the variable can recognize the variable.

As soon as the function finishes running, the local variables will be deleted.


Global JavaScript Variables

The variable declared outside the function is a global variable, and all scripts and functions on the webpage can access it.


The Lifetime of JavaScript Variables

The lifetime of JavaScript variables starts at the time they are declared.

Local variables will be deleted after the function runs.

Global variables will be deleted after the page is closed.


Assign Values to Undeclared JavaScript Variables

If you assign a value to a variable that has not been declared, the variable will automatically be used as an attribute of the window.

This statement:

carname="Dodge";

An attribute carname of window will be declared.

Global variables created by assigning values to undeclared variables in non-strict mode are configurable properties of global objects and can be deleted.

var var1 = 1; // global attributes cannot be configured
var2 = 2; // No var declaration is used, global attributes can be configured

console.log(this.var1); // 1
console.log(window.var1); // 1
console.log(window.var2); // 2

delete var1; // false, cannot be deleted
console.log(var1); //1

delete var2;
console.log(delete var2); // true
console.log(var2); // has been deleted, the error variable is not defined