JavaScript function
Example
Declare a function that outputs "Hello World" when it is called:
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World!";
}
// Call the function
myFunction();
More examples below.
Description
The function
statement declares a function.
A declared function is "saved for later use", and will be executed later, when it is invoked (called).
In JavaScript, functions are objects, and they have both properties and methods.
A function can also be defined using an expression (See Function Definitions).
Read our JavaScript Tutorial to learn all you need to know about functions. Start with the introduction chapter about JavaScript Functions and JavaScript Scope. For more detailed information, see our Function Section on Function Definitions, Parameters, Invocation and Closures.
See Also:
Syntax
code to be executed
}
Parameters
The name of the function.
Naming rules: same as JavaScript variables.
A set of arguments (parameter names), separated by commas.
The arguments are real values received by the function from the outside.
Inside the function, the arguments are used as local variables.
If a function is called with a missing argument, the value of the missing argument is set to
undefined
.
More Examples
A function with different arguments can produce different results.
Convert Fahrenheit to Celsius:
return (5/9) * (fahrenheit-32);
}
Functions can be used as variables.
Instead of:
text = "The temperature is " + temp + " Centigrade";
You can use:
JavaScript functions have a built-in object called arguments.
The arguments.length property returns the number of arguments received by the function:
return arguments.length;
}
Click to call a function that outputs "Hello World":
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
When a function expression is stored in a variable, the variable contains a function:
When a function is stored in a variable, the variable can be used as a function:
let z = x(4, 3);
Related Pages
JavaScript Tutorial: JavaScript Functions
JavaScript Tutorial: JavaScript Scope
JavaScript Tutorial: JavaScript Function Definitions
JavaScript Tutorial: JavaScript Function Parameters
JavaScript Tutorial: JavaScript Function Invocation
JavaScript Tutorial: JavaScript Function Closures
JavaScript Reference: JavaScript return Statement
Browser Support
function
is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |