JavaScript Function

A function in JavaScript is a section of code that completes a particular job and can be accessed from other areas of a program.

This is the basic syntax for creating a function:

function functionName(parameter1, parameter2, ...) { // code to be executed return returnValue; }

The function keyword is used to define the function, followed by the functionName which is the name of the function. Inside the parentheses, you can include one or more parameters that the function can accept. These parameters act as placeholders for values that will be passed into the function when it is called.

The code inside the function block is the actual code that is executed when the function is called. You can use the parameters and any other JavaScript code to perform the task that the function is designed to do.

The return statement is used to specify the value that the function will return to the caller. This statement is optional, and if it is not included, the function will return undefined.

Example:

function multiply(num1, num2) { let result = num1 * num2; return result; } let product = multiply(2, 3); 
console.log(product);

In this example, the multiply() function takes two parameters, num1 and num2, and returns their product. When the function is called with multiply(2, 3), the num1 parameter is set to 2, and the num2 parameter is set to 3. The function then multiplies these two values together, and assigns the result to the result variable. Finally, the function uses the return statement to return the value of result.

The value returned by the function is assigned to the product variable, which is then printed to the console using console.log(). In this case, the output would be 6.

Last updated