Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Functions

JavaScript Functions


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, preceded by the keyword function:

function

functionname

()

{

    

// execute code

}

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

A function can be called directly when an event occurs (such as when the user clicks a button), and 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 case as its name.

Calling a Function with Parameters

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

These parameters can be used inside the function.

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

myFunction(

argument1,argument2

)

When you declare a function, 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 alert "Welcome Harry Potter, the Wizard" when the button is clicked.

Functions are flexible; you can call the same function with different parameters to produce different messages:

Example

<button onclick=">

myFunction('Harry Potter','Wizard')

"

Click here

button

<button onclick="myFunction('Bob','Builder')">

Click here

button

Try it »

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


Functions with a Return Value

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

This can be achieved by using the return statement.

When a return statement is used, the function stops executing and returns the specified value.

Syntax

function myFunction()

{

    var x=5;

    return x;

}

The above function returns the value 5.

Note: The entire JavaScript does not stop executing, only the function. JavaScript will continue executing code from the place 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()".

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 based on the parameters passed into 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 »

The return statement can also be used when you only want to exit a 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

Variables declared inside a JavaScript function (using var) arelocalvariables, so they can only be accessed inside the function. (The scope of such a 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 it.

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


Global JavaScript Variables

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


The Lifetime of JavaScript Variables

The lifetime of a JavaScript variable starts at the time it is declared.

Local variables are deleted after the function runs.

Global variables are deleted after the page is closed.


Assigning a Value to an Undeclared JavaScript Variable

If you assign a value to a variable that has not been declared, the variable is automatically made a property of window.

This statement:

carname="Volvo";

declares a property carname of window.

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); // 已经删除 报错变量未定义