Your Page Title
πŸ”

    πŸ“˜ JavaScript apply()

    βœ… 1. What Is apply()?

    The apply() method allows you to invoke a function, while explicitly specifying:

    • The this context
    • The arguments (as an array or array-like object)
    jsCopyEditfunction sayHello() {
      console.log("Hello, " + this.name);
    }
    
    const user = { name: "Alice" };
    
    sayHello.apply(user); // Hello, Alice
    

    πŸ“Œ 2. Syntax

    jsCopyEditfunc.apply(thisArg, [arg1, arg2, ...])
    
    • func: the function to be called
    • thisArg: the value to use as this when the function runs
    • []: an array of arguments

    πŸ“Œ 3. Example: Passing Arguments with apply()

    jsCopyEditfunction introduce(language1, language2) {
      console.log(`${this.name} speaks ${language1} and ${language2}`);
    }
    
    const person = { name: "Bob" };
    
    introduce.apply(person, ["English", "French"]);
    // Output: Bob speaks English and French
    

    πŸ“Œ 4. Difference Between call() and apply()

    Featurecall()apply()
    ArgumentsPassed individuallyPassed as an array
    Use caseWhen arguments are knownWhen arguments are in array

    Example:

    jsCopyEditfunc.call(thisArg, arg1, arg2);
    func.apply(thisArg, [arg1, arg2]);
    

    πŸ“Œ 5. Use Case: Math.max with Arrays

    You can’t pass an array directly to Math.max, but you can use apply():

    jsCopyEditconst nums = [10, 30, 5, 8];
    const max = Math.max.apply(null, nums);
    
    console.log(max); // 30
    

    βœ… Works because apply() spreads the array into individual arguments.


    πŸ“Œ 6. Use Case: Borrowing Methods

    jsCopyEditconst arrayLike = {
      0: "a",
      1: "b",
      length: 2
    };
    
    // Borrow Array method
    const realArray = Array.prototype.slice.apply(arrayLike);
    
    console.log(realArray); // ["a", "b"]
    

    πŸ“Œ 7. ES6 Replacement: Spread Operator

    In modern JavaScript, the spread syntax often replaces apply():

    jsCopyEditMath.max(...[10, 20, 30]); // 30
    

    But apply() is still useful in older environments and for method borrowing.


    πŸ§ͺ Practice Tasks

    1. Create a function greetUser(greeting) and use apply() to pass { name: "Sam" } and ["Good morning"].
    2. Use Math.min.apply() to find the smallest number in [3, 8, -5, 12].

    🧠 Summary

    FeatureDescription
    func.apply()Calls a function with this and arguments (as an array)
    Best forArrays, array-like objects, dynamic arguments
    AlternativeUse spread ... in modern JavaScript

    Would you like:

    • πŸ“„ PDF or print-friendly version?
    • πŸ’» Live playground (e.g., CodePen or JSFiddle)?
    • 🧠 Short quiz or flashcards?