JavaScript Function
JavaScript functions are used to perform operations and can be called multiple
times to reuse the code.
Advantages Of JavaScript Function
The main advantages of JavaScript functions are twofold.
1. Code reusability: We can call a
function multiple times, which helps save coding effort.
2. Less coding: It makes our program more
compact, as we don’t need to write multiple lines of code each time to perform
a common task.
Syntax:
function functionName(parameters) {
// code to be executed
}
JavaScript Function Arguments
We can call a function by passing arguments. Let's look at an example of a
function with one argument.
Example:
<Script>
function sayHello() {
console.log("Hello, World!");
}
sayHello();
</Script>
Output:
Hello, Word!"
Function With Return Values
We can call a function that returns a value and use it in our program. Let’s
look at an example of a function that returns a value.
Example:
<Script>
function addFive(num) {
return num + 5;
}
let result = addFive(10);
console.log(result);
let result2 = addFive(20);
console.log(result2);
</Script>
Output:
15
25
JavaScript Function Object
In JavaScript, the Function constructor is used to create a new Function
object and execute code globally. However, calling the constructor directly
creates a function dynamically, but it poses security risks.
Syntax
new Function(arg1, arg2, ..., argN, functionBody)
Parameter
arg1, arg2, ..., argn - These represent the arguments used by the function.
`functionBody` represents the function definition.
JavaScript Function Methods
Let’s examine function methods along with their descriptions.
Example 1:
Let’s look at an example that displays the sum of given numbers.
<Script>
function addNumbers(a, b) {
return a + b;
}
console.log(addNumbers(5, 10));
</Script>
Output:
15
Example 2:
Let’s look at an example that displays the power of a given value.
<Script>
function calculatePower(base, exponent) {
return Math.pow(base, exponent);
}
</Script>
console.log(calculatePower(2, 3));
Output:
8
More topic in JavaScript