JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Function Apply


📘 JavaScript apply() Method – Call a Function with Array Arguments

The apply() method lets you invoke a function with a specified this context and an array (or array-like object) of arguments.


🔹 Syntax

func.apply(thisArg, [argsArray]);
  • thisArg: The value to use as this inside the function.

  • argsArray: An array (or array-like object) of arguments.


🔹 Example 1 – Basic Usage

function greet(city, country) {
  console.log(`Hello ${this.name} from ${city}, ${country}`);
}

const person = { name: "Alice" };

greet.apply(person, ["Delhi", "India"]);
// Output: Hello Alice from Delhi, India

🔹 Example 2 – Using Math.max() with apply

const numbers = [4, 9, 2, 7];

const max = Math.max.apply(null, numbers);
console.log(max); // Output: 9

🔹 Difference: call() vs apply()

Method Argument Format
call() Comma-separated values
apply() Array of arguments

Practice Questions

Q1. Create a function showInfo that logs this.name, this.age. Use apply() to invoke it with { name: "Ravi", age: 28 }.

Q2. Write a function sum(a, b) and call it using apply() with [4, 6] as arguments and a dummy this object.

Q3. Create an object student with name: "Anu" and use a standalone printName() function with apply() to print her name.

Q4. Use apply() with Math.min to find the smallest number in [2, 8, 5, 1, 9].

Q5. Create a function introduce(city, country) and use apply() to bind it with a person object and pass array arguments.

Q6. Create a function calculateArea(length, width) and use apply() to pass [5, 3] as arguments.

Q7. Define a sayHello function and use apply() to call it with different this values like { name: "Sara" }, { name: "Tom" }.

Q8. Write a function showDetails() that logs this.id and this.role. Use apply() with { id: 101, role: "Admin" }.

Q9. Create a function multiply(a, b, c) and call it using apply() with array [2, 3, 4]. Print the result.

Q10. Write a function concatStrings(a, b, c) and use apply() to pass ["JavaScript", "is", "fun"] and print "JavaScript is fun".


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top