JavaScript Functions
- A JavaScript function is a block of code crafted to carry out a specific task.
- This function is executed whenever it is invoked or called by something within the code.
Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
let result = myFunction(4, 3);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
JavaScript Function Syntax
- In JavaScript, a function is created using the function keyword, followed by a name, and then a pair of parentheses ().
- The function's name can include letters, digits, underscores, and dollar signs, adhering to the same naming rules as variables.
- Parameters for the function are listed inside the parentheses, separated by commas: (parameter1, parameter2, ...).
- The actual code that the function will execute is enclosed within curly brackets: {}.
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function Invocation
- In JavaScript, function parameters are defined within the parentheses of the function declaration.
- When a function is called, it receives values known as arguments that correspond to these parameters.
- Within the function's body, these arguments act as local variables, scoped only to the function itself.
Function InvocationThe code within a JavaScript function is executed when the function is invoked, which can happen in several ways:An event triggers the function, such as a user clicking a button.The function is called directly from JavaScript code.The function invokes itself automatically (also known as an immediately invoked function expression or IIFE).As you progress through this tutorial, you'll gain deeper insights into different ways functions can be invoked and how they operate.
Function Return
- When a JavaScript function encounters a return statement, it ceases execution immediately.
- If the function is called from within another part of the code, execution will resume just after the point where the function was invoked.
- Often, functions calculate a return value that is then sent back to the function's caller, providing a result from the function's execution.
Example
Calculate the product of two numbers, and return 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;
}
Calculate the product of two numbers, and return the result:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>
Why Functions?
- Functions enable code reuse within your applications, allowing you to write a set of instructions once and use them repeatedly.
- By crafting functions, you can call the same code multiple times across different parts of your program.
- Additionally, you can execute the same function with various arguments to yield diverse outcomes, enhancing the flexibility and functionality of your code.
The () Operator
- The parentheses () operator is used to invoke or call a function in JavaScript, signaling the execution of the function's code.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius(77);
Convert Fahrenheit to Celsius:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Invoke (call) a function that converts from Fahrenheit to Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
let value = toCelsius(77);
document.getElementById("demo").innerHTML = value;
</script>
</body>
</html>
- Providing incorrect parameters when calling a function can lead to unexpected results or errors in the output.
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius()
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Invoke (call) a function to convert from Fahrenheit to Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
let value = toCelsius();
document.getElementById("demo").innerHTML = value;
</script>
</body>
</html>
Referring to a function by its name without following it with parentheses () returns the function itself, not the result of its execution.
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
let value = toCelsius;
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Accessing a function without () returns the function and not the function result:</p>
<p id="demo"></p>
<script>
function toCelsius(f) {
return (5/9) * (f-32);
}
let value = toCelsius;
document.getElementById("demo").innerHTML = value;
</script>
</body>
</html>
Note
From the examples provided, toCelsius refers to the function object itself, while toCelsius() calls the function and refers to the result of its execution
Functions Used as Variable Values
Functions in JavaScript can be utilized just like variables, making them versatile for use in formulas, assignments, and various calculations.
Example
Instead of using a variable to store the return value of a function:
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
You can use the function directly, as a variable value:
let text = "The temperature is " + toCelsius(77) + " Celsius";
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Using a function as a variable:</p>
<p id="demo"></p>
<script>
let text = "The temperature is " + toCelsius(77) + " Celsius.";
document.getElementById("demo").innerHTML = text;
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
</script>
</body>
</html>
- As you progress through this tutorial, you'll discover more in-depth information and advanced techniques regarding functions.
Local Variables
- Variables declared inside a JavaScript function are local to that function. They can only be accessed and used within the function itself.
Example
// code here can NOT use carName
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
// code here can NOT use carName
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Outside myFunction() carName is undefined.</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let text = "Outside: " + typeof carName;
document.getElementById("demo1").innerHTML = text;
function myFunction() {
let carName = "Volvo";
let text = "Inside: " + typeof carName + " " + carName;
document.getElementById("demo2").innerHTML = text;
}
myFunction();
</script>
</body>
</html>
Local variables are scoped to their respective functions, allowing variables with the same name to be used in different functions without conflict.
These local variables are created when the function begins execution and are deleted once the function has completed, ensuring efficient memory management.