JAVASCRIPT Tutorial

Simple Function

What is a Function?

A function is a block of code that performs a specific task and returns a value.

Function Declaration

To declare a function, use the following syntax:

function functionName(parameters) {
  // Function code
}
  • functionName: A unique name for the function.
  • parameters: Optional values that the function needs to perform its task.

Function Call

To call a function, use the following syntax:

functionName(arguments);
  • arguments: The actual values passed to the function.

Return Value

A function can return a value using the return statement.

function functionName() {
  return value;
}

Calculation

Functions can perform calculations by using variables, operators, and control flow statements.

JavaScript Example

// Function to calculate the area of a triangle
function calculateArea(base, height) {
  return (base * height) / 2;
}

// Call the function and store the result in a variable
const area = calculateArea(5, 3);

console.log(`The area of the triangle is: ${area}`);

In this example:

  • The calculateArea function is defined with two parameters, base and height.
  • The function returns the area of a triangle using the formula (base * height) / 2.
  • The function is called with arguments 5 and 3, and the result is stored in the area variable.
  • The calculated area is printed to the console.