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.
JavaScript Function Syntax
The syntax for declaring a function is provided below.
Statement:
function functionName(parameters) {
// code to be executed
}
JavaScript functions can accept zero or more arguments.
JavaScript Function Example
Let’s look at a simple example of a JavaScript function that has no arguments.
<Script>
function sayHello() {
console.log("Hello, World!");
}
sayHello();
</Script>
Output:
Hello, World!
JavaScript Function Arguments
We can call a function by passing arguments. Let's look at an example of a
function with one argument.
<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.
<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.
JavaScript Function Object Examples
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