JavaScript function is a block of code that performs a specific task and can be called or invoked multiple times throughout a program. In this way, functions can help make code more modular, reusable, and easier to maintain.
function functionName(parameter1, parameter2, ...) {
// function body
return result;
}
Functions are defined using the function
keyword and can accept input parameters and return output values.
Or use Function expression, which is another way to define a function. Instead of using the function
keyword, a function expression defines a function as a value assigned to a variable.
const greet = function(name) {
console.log(`Hello, ${name}!`);
};
greet('Alice'); // Output: Hello, Alice!
JavaScript Function example
Simple example code of a simple function that takes two parameters and returns their sum:
<!DOCTYPE html>
<html>
<body>
<script>
function addNumbers(a, b) {
const sum = a + b;
return sum;
}
const result = addNumbers(5, 7);
console.log(result);
</script>
</body>
</html>
Output:
Calling a Function
To call or invoke a function in JavaScript, you simply use the name of the function followed by parentheses ()
containing any necessary arguments.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Alice'); // Hello, Alice!
Function Return
Functions can also return a value by using the return
keyword.
function add(x, y) {
return x + y;
}
const result = add(3, 5);
console.log(result); // Output: 8
Functions help to organize code, reduce redundancy, and increase reusability. They allow you to break down complex tasks into smaller, more manageable pieces and provide a simple, abstract interface to the user. By using functions, you can make your code more modular, easier to understand, and simpler to maintain.
Do comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version