Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Function Apply in JavaScript

Function Apply in JavaScript

?? Function.prototype.apply() in JavaScript


What is apply()?

  • apply() is a method available on all JavaScript functions.

  • It calls a function with a given this value, and arguments provided as an array (or array-like object).

  • Useful when you want to control the this context and pass arguments dynamically.


Syntax

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

  • argsArray: An array or array-like object of arguments to pass to the function.


Example 1: Basic Usage

function greet(greeting, punctuation) {  console.log(greeting + ", " + this.name + punctuation);}const person = { name: "Alice" };// Call greet with 'person' as this and arguments in an arraygreet.apply(person, ["Hello", "!"]);  // Output: Hello, Alice!

Example 2: Using apply to Find Max in an Array

const numbers = [5, 6, 2, 9, 1];// Math.max expects separate arguments, not an arrayconst max = Math.max.apply(null, numbers);console.log(max);  // 9

Difference Between apply() and call()

  • Both set the this context.

  • call() accepts arguments one by one.

  • apply() accepts arguments as an array.

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

Why Use apply()?

  • When the number of arguments is unknown or already in an array.

  • When you want to reuse functions with different contexts dynamically.


Summary

Aspectapply()
Calls a functionYes
Sets thisYes
ArgumentsAs an array or array-like object

Want me to show you how to implement your own version of apply() or how to use it with constructor functions?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql