WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Functions


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


Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Test case</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, with the keyword function:

function functionname()
{
    // Execute code
}

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

Functions can be called directly when an event occurs (such as when the user clicks a button), and can be called from anywhere by JavaScript.

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

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.


Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Example

Calculate the product of two numbers, and return the result:

var x = myFunction(4, 3);        // Function is called, return value will end up in x

function myFunction(a, b) {
    return a * b;                // Function returns the product of a and b
}

The result in x will be:

12
Try it yourself »

Example

Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
Try it yourself »

The () Operator Invokes the Function

Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Example

Accessing a function without () will return the function definition:

function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Try it Yourself »

Functions Used as Variables

In JavaScript, you can use functions the same way as you use variables.

Example

You can use:

var text = "The temperature is " + toCelsius(77) + " Celsius";

Instead of:

var x = toCelsius(32);
var text = "The temperature is " + x + " Celsius";
Try it Yourself »

Local JavaScript Variables

A variable declared inside a 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 will recognize it.

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


Global JavaScript Variables

The variables declared outside the function are global variables, which are accessible to all scripts and functions on the web page.


Lifetime of JavaScript variables

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

Local variables are deleted after the function runs.

Global variables are deleted after the page is closed.


Assign a value to an undeclared JavaScript variable

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

This statement:

carname = "Volvo";

A property carname of window will be declared.

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

var var1 = 1; // Non-configurable global attributes
var2 = 2; // No var declaration, configurable global properties

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

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

delete var2; 
console.log(delete var2); // true
console.log(var2); // Deleted error variable is not defined