The code within a function is triggered to execute under various circumstances:
– When an event takes place (like a user clicking a button).
– When called explicitly from JavaScript code.
– Automatically, through self-invocation.
Further details about function invocation will be covered later in this tutorial.
Upon encountering a return statement in JavaScript, the function halts its execution.
If the function was called from a statement, JavaScript will proceed to execute the code following that invoking statement.
Functions frequently produce a return value, which is then sent back to the caller.
Compute the multiplication of two numbers and provide the outcome as the result.
// Function is called, the return value will end up in x let x = myFunction(4, 3); function myFunction(a, b) { // Function returns the product of a and b return a * b; } |
Why Functions? Functions empower code reusability, enabling you to create code that can be utilized repeatedly. This flexibility allows for the application of the same code with various arguments, yielding diverse results. |
The () operator triggers the execution of the function.
Translate Fahrenheit to Celsius.
function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } let value = toCelsius(77); |
Using improper parameters to access a function may yield an inaccurate result.
function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } let value = toCelsius(); |
When accessing a function without (), it returns the function itself rather than the function’s result.
function toCelsius(fahrenheit) { let value = toCelsius; |
NOTE:As evident from the examples provided, “toCelsius” denotes the function object, whereas “toCelsius” denotes the function’s result. |
Functions can be employed akin to variables, across various formulas, assignments, and calculations.
Instead of utilizing a variable to hold the returned value of a function:
let x = toCelsius(77); let text = “The temperature is “ + x + ” Celsius”; |
You can directly employ the function as a value for a variable.
let text = “The temperature is “ + toCelsius(77) + ” Celsius”; |
Variables declared within a JavaScript function are considered Local to that function.
These local variables are accessible solely from within the function.
// code here can NOT use carName function myFunction() { let carName = “Volvo”; // code here CAN use carName } // code here can NOT use carName |
Given that local variables are confined to their respective functions, it’s possible to use variables with identical names in separate functions.
Local variables are instantiated upon the initiation of a function and are discarded once the function concludes.