Different JavaScript Functions

Different JavaScript Functions

JavaScript is a versatile programming language that supports various types of functions. Here are some common types of functions in JavaScript:

  1. Function Declarations:

     function calculateTax(income) {
       const taxRate = 0.2;
       return income * taxRate;
     }
    
  2. Function Expressions:

     const greet = function(name) {
       return `Hello, ${name}!`;
     };
    
  3. Arrow Functions:

     const square = (num) => num * num;
    
  4. Anonymous Functions:

     const logMessage = function(message) {
       console.log(message);
     };
    
  5. Immediately Invoked Function Expressions (IIFE):

     (function() {
       const today = new Date();
       console.log(`Today is ${today.toDateString()}`);
     })();
    
  6. Higher-Order Functions:

     const operate = (a, b, operation) => operation(a, b);
    
     const result = operate(5, 3, (x, y) => x + y);
    
  7. Callback Functions:

     function fetchData(url, callback) {
       // Simulating an asynchronous API call
       setTimeout(() => {
         const data = { result: 'Some data' };
         callback(data);
       }, 1000);
     }
    
     fetchData('https://example.com/api/data', function(data) {
       console.log('Data received:', data.result);
     });
    
  8. Anonymous Arrow Functions:

     const numbers = [1, 2, 3, 4];
    
     const squared = numbers.map((num) => num * num);
    
  9. Generator Functions:

     function* generateSequence() {
       yield 'Step 1';
       yield 'Step 2';
       yield 'Step 3';
     }
    
     const sequenceGenerator = generateSequence();
     console.log(sequenceGenerator.next().value); // 'Step 1'
    
  10. Async Functions:

    async function fetchData(url) {
      let response = await fetch(url);
      let data = await response.json();
      return data;
    }
    
  11. Currying Functions:

    function curry(fn) {
      return function curried(...args) {
        if (args.length >= fn.length) {
          return fn(...args);
        } else {
          return function (...args2) {
            return curried(...args, ...args2);
          };
        }
      };
    }
    
    const addCurried = curry((a, b, c) => a + b + c);
    console.log(addCurried(1)(2)(3)); // 6
    

These examples showcase how each type of function can be applied in various real-world scenarios.