JavaScript Function


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

Examples

<!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 Yourself »


JavaScript Function Syntax

A function is a block of code wrapped in curly braces, preceded by the keyword function:

function functionname()
{
    // Execute code
}

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

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

lamp JavaScript is case-sensitive. The keyword function must be lowercase, and the function must be called with the same capitalization as the function name.


Call 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 within the function.

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

myFunction(argument1,argument2)

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

function myFunction(var1,var2)
{
Code
}

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

Examples

<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 Yourself »

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

Functions are very flexible. You can call the function with different parameters, and it will give different messages:

Examples

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

Try it Yourself »

Depending on which button you click, the example above will alert "Welcome Harry Potter, the Wizard" or "Welcome Bob, the Builder".


Functions with Return Values

Sometimes, we want a function to return a value to the place that called it.

This can be done by using the return statement.

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

Syntax

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

The function above will return the value 5.

Note:The entire JavaScript does not stop executing; only the function does. JavaScript will continue to execute code from where the function was called.

The function call will be replaced by the return value:

var myVar=myFunction();

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

You can also use the return value without saving it as a variable:

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 make the return value depend on the parameters passed to the function:

Examples

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 Yourself »

You can also use the return statement when you simply 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 code above will exit the function and will not calculate the sum of a and b.


Local JavaScript Variables

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

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

Local variables are deleted as soon as the function is completed.


Global JavaScript Variables

Variables declared outside a function areglobalvariables, and all scripts and functions on a web page can access them.


JavaScript Variable Lifetime

The lifetime of JavaScript variables begins when they are declared.

Local variables are deleted after the function runs.

Global variables are 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 become a property of window.

This statement:

carname="Volvo";

will declare a property of window called carname.

In non-strict mode, a global variable created by assigning a value to an undeclared variable is a configurable property of the global object and can be deleted.

var var1 = 1; // 不可配置全局属性
var2 = 2; // 没有使用 var 声明,可配置全局属性

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

delete var1; // false 无法删除
console.log(var1); //1

delete var2; 
console.log(delete var2); // true
console.log(var2); // 已经删除 报错变量未定义
Other Extensions