Functions In JavaScript

Functions In JavaScript

What Is Function

function is a block of code which can be use many times in our application.
this function can be of without parameter or with parameter.

//Without Parameter or Arguments
function Add() {
  var a = 10;
  var b = 20;
  console.log(a + b);
}
Add();

//With Parameters or Arguments
function Add(a,b) {
  console.log(a + b);
}
Add(10,20);

//Advanced Code:
// Function to calculate the area of a rectangle
function calculateArea(length, width) {
    return length * width;
}

// Using the function
const area1 = calculateArea(5, 10);
console.log("Area 1:", area1);  // Output: 50

const area2 = calculateArea(3, 7);
console.log("Area 2:", area2);  // Output: 21

Types Of Writing Function

//1.
function Add() {
  var a = 10;
  var b = 20;
  console.log(a + b);
}
Add();

//2.
function Add() {
    var a = 10;
    var b = 20;
    return a + b;
}
console.log(Add());

//3. Array Function
const add = () => {
    var a = 10;
    var b = 20;
    console.log(a + b);
}
add();

//4. Arrow Function With Arguments

const add = (a, b) => {
    return a + b;
}
console.log(add(10,20));

Advantages

  1. Reusability: Functions allow you to define a block of code once and use it multiple times throughout your program. This reduces redundancy and makes your code more efficient.

  2. Modularity: Functions promote a modular approach to programming. You can break down your code into smaller, manageable chunks, each responsible for a specific task. This makes your code easier to understand, maintain, and debug.

  3. Abstraction: Functions allow you to abstract away complex operations behind a simple interface. For example, you can create a function that calculates the square of a number without needing to know the mathematical formula each time you want to use it.

  4. Encapsulation:

  5. Code Organization:

  6. Testing and Debugging:

Did you find this article valuable?

Support Abdul Basit blog by becoming a sponsor. Any amount is appreciated!