A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked.
Inside the function, the arguments are used as local variables.
![]() |
A Function is much the same as a Procedure or a Subroutine, in other programming languages. |
---|
The code inside the function will execute when "something" invokes (calls) the function:
You will learn a lot more about function invocation later in this tutorial.
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":
Calculate the product of two numbers, and return the result:
The result in x will be:
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
Convert Fahrenheit to Celsius:
Using the example above, toCelsius refers to the function object, and toCelcius() refers to the function result.
Accessing a function without () will return the function definition:
In JavaScript, functions can be used as variables:
Instead of:
You can use:
![]() |
You will learn a lot more about functions later in this tutorial. |
---|