JavaScript Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure – a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.
A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when “something” calls it.
Syntax
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).
function name(parameter1, parameter2, parameter3) { code to be executed }
Example
In this example, we call a function which performs an addition and returns the result
The code inside the function will execute when “something” invokes (calls) the function:
- When an event occurs
- When it is called from JavaScript code
- Automatically
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was called 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:
Why Functions?
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.
Example: Convert Fahrenheit to Celsius: