JavaScript functions are employed for executing tasks. The JavaScript function can be invoked multiple times, allowing for the reuse of code.
In JavaScript, a function is declared using the function keyword, followed by a name and parentheses ().
Function names in JavaScript are allowed to include letters, digits, underscores, and dollar signs, adhering to the same rules as variables.
The parentheses in a JavaScript function can contain parameter names, which are separated by commas. For example: (parameter1, parameter2, ...)
The executable code for a JavaScript function is enclosed within curly brackets: {}.
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
The parameters of a function are declared within the parentheses () in the function definition.
Function arguments refer to the values passed to the function when it's called.
Within the function, these arguments (parameters) act as local variables.
The code within the function will run when it is called by "something:
When a certain event happens (like a user clicking a button),
When it's called from JavaScript code,
Or automatically (self-invoked).
When JavaScript encounters a return statement, the function execution halts.
If the function was called within a statement, JavaScript will "return" to continue executing the code after that statement.
Functions frequently calculate a return value, which is then passed back to the caller.
Example:-
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
</head>
<body>
<h1>JavaScript Functions</h1>
<p>call a function that converts from Fahrenheit to Celsius:</p>
<p id="demo"></p>
<script>
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit - 32);
}
let result = toCelsius(100);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Output:-
call a function that converts from Fahrenheit to Celsius:
37.77777777777778
Functions enable code reusability, allowing you to write code once and utilize it multiple times.
They facilitate the creation of code that can be employed repeatedly.
By utilizing the same code with various arguments, you can generate diverse outcomes
We can invoke a function by providing arguments. Let's explore an example of a function that accepts a single argument.
<!DOCTYPE html>
<html>
<head>
<title>Cube Calculator</title>
</head>
<body>
<script>
function calculateCube(number){
alert(number * number * number);
}
</script>
<form>
<input type="button" value="Calculate Cube" onclick="calculateCube(8)"/>
</form>
</body>
</html>