JavaScript Functions
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).
JavaScript Function Syntax
A JavaScript function is created using the function
keyword, followed by a name and parentheses ()
.
Function names can include letters, numbers, underscores, and dollar signs. It follows the same rules as variables.
You can put names of parameters inside parentheses, separated by commas, like this:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function
name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters
are written within the ()
parentheses when defining a function.
Function arguments
are the values that the function gets when it's used.
In the function, the input values (called parameters) act like variables that belong only to that function.
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)
In this tutorial, you'll discover more about how functions are used, but we'll delve deeper into it later.
Function Return
When JavaScript encounters a return
statement,
the function will immediately halt.
If you use a function in JavaScript as part of your code, once that function is done, JavaScript will go back and continue with the code that comes after the function call in your program.
Functions usually calculate a result, which is then sent back to the part of the code that called the function.
Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments
, to produce different results.
The () Operator
The () operator
invokes (calls) the function:
Using the wrong inputs when calling a function might give you the wrong result:
Accessing a function without ()
returns the function and not the function result:
Note :
As you see from the examples above, toCelsius
refers to the function object, and
toCelsius()
refers to the function result.
Functions Used as Variable Values
You can use functions just like you use variables in various formulas, assignments, and calculations.
You will learn a lot more about functions later in this tutorial.
Local Variables
When you create variables inside a JavaScript function, they are limited to that specific function and can't be accessed from outside.
Variables created inside a function can only be used within that function.
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Inside a function, we make local variables at the beginning and remove them when the function finishes.