#atom
Functions in JavaScript are first-class objects, meaning they can be assigned to variables, passed as arguments, and returned from other functions. They are used to encapsulate reusable code and perform specific tasks.

Ways to Define Functions:

  1. Function Declaration:

    function greet() {
        console.log('Hello!');
    }
    
  2. Function Expression:

    const greet = function() {
        console.log('Hello!');
    };
    
  3. Arrow Function (ES6):

    const greet = () => {
        console.log('Hello!');
    };
    
  4. Constructor Function:

    const greet = new Function('console.log("Hello!")');
    

Methods and Properties of Functions:

  1. name Property: Returns the name of the function.

    function greet() {}
    console.log(greet.name); // "greet"
    
  2. length Property: Returns the number of parameters the function expects.

    function add(a, b) {}
    console.log(add.length); // 2
    
  3. call() Method: Calls a function with a specific this value and arguments provided individually.

    function greet(message) {
        console.log(`${message}, ${this.name}`);
    }
    const person = { name: 'Alice' };
    greet.call(person, 'Hello'); // "Hello, Alice"
    
  4. apply() Method: Similar to call(), but arguments are provided as an array.

    greet.apply(person, ['Hello']); // "Hello, Alice"
    
  5. bind() Method: Creates a new function with a specific this value and optional arguments.

    const greetAlice = greet.bind(person, 'Hello');
    greetAlice(); // "Hello, Alice"
    
  6. toString() Method: Returns the function's source code as a string.

    console.log(greet.toString()); // "function greet() { console.log('Hello!'); }"
    

The this Keyword in Functions:

Example:

const person = {
    name: 'Alice',
    greet: function() {
        console.log(`Hello, ${this.name}`);
    }
};
person.greet(); // "Hello, Alice"

Connections:


Connections:


Sources: