Javascript Defining functions

A function in JavaScript is a section of code that completes a certain task. Code can be made more modular and organized into reusable parts with the help of functions. The JavaScript syntax for defining a function is as follows:

Syntax:

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

A new function is defined with the function keyword. The name of the function, functionName, may be any legal identifier. You can specify any number of parameters that the function accepts as input inside the parenthesis. Commas are used to separate these parameters.

Curly braces enclose the code that will be run. Any legitimate JavaScript code, including statements, expressions, and other function calls, can be written inside the curly braces.

The value that the function returns is specified in the return statement. This is optional; the function returns undefined if no return statement is supplied.

Here is an illustration of a function that determines a rectangle’s area:

function rectangleArea(width, height) {
    var area = width * height;
    return area;
}

In this example, rectangleArea is the name of the function, and width and height are the parameters that the function takes as input. Inside the function, the area of the rectangle is calculated by multiplying width and height and then returned using the return statement. To call this function and get the area of a rectangle with a width of 5 and a height of 10, you can use the following code:

var area = rectangleArea(5, 10);
console.log("Area of rectangle = " + area);

This will output Area of rectangle = 50 to the console, which is the area of a rectangle with a width of 5 and a height of 10.