In JavaScript, a function is a block of code that performs a specific task and can be called multiple times with different inputs or arguments. Writing a simple function in JavaScript involves defining the function using the function keyword, specifying any input parameters or arguments, and writing the code to be executed when the function is called.
Here is an example of a simple function in JavaScript that takes two numbers as input and returns their sum:
function addNumbers(num1, num2) {
var sum = num1 + num2;
return sum;
}
In this example, the function is named addNumbers, and it takes two parameters num1 and num2. The code inside the function calculates the sum of num1 and num2 and stores it in a variable named sum. Finally, the function returns the value of sum using the return keyword.
To call this function and get the result, we can pass two numbers as arguments:
var result = addNumbers(5, 7);
console.log(result); // Outputs 12
In this example, we pass the numbers 5 and 7 as arguments to the addNumbers function, which calculates their sum and returns the value 12. The value of result is then printed to the console using the console.log function.
Functions in JavaScript can be more complex and can perform a variety of tasks, from simple arithmetic operations to complex logic and data manipulation. They are a powerful and essential feature of the language and are used extensively in both front-end and back-end development.
In summary, to write a simple function in JavaScript, you need to define the function using the function keyword, specify any input parameters or arguments, and write the code to be executed when the function is called.