
How to write a function in JavaScript
To write a function in JavaScript, you can use the function keyword followed by the function name, parentheses for parameters (if any), and curly braces {} to define the function’s body. Here’s the basic syntax:
function functionName(parameter1, parameter2) {
// Function body
// Code to be executed when the function is called
// You can perform operations, define variables, and return values
}Here’s an example of a simple function that adds two numbers and returns the result:
function addNumbers(num1, num2) {
var sum = num1 + num2;
return sum;
}
// Calling the function and storing the result
var result = addNumbers(5, 3);
console.log(result); // Output: 8In this example, the addNumbers function takes two parameters num1 and num2. It calculates the sum of the two numbers and returns the result using the return keyword. The function is then called with arguments 5 and 3, and the returned value is stored in the result variable. Finally, the value of result is printed to the console using console.log().
You can define and use functions in JavaScript to encapsulate reusable blocks of code, perform operations, manipulate data, and more.