Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Function Apply

JS Function Apply

With the apply() method, you can write a method that can be used on different objects.

The JavaScript apply() Method

The apply() method is similar to the call() method (previous chapter).

					 
        
          const person = {
            fullName: function() {
              return this.firstName + " " + this.lastName;
            }
          }

          const person1 = {
            firstName: "Mary",
            lastName: "Doe"
          }

          person.fullName.apply(person1); // "Mary Doe"
        
      
The Difference Between call() and apply()

The call() method takes arguments separately.

The apply() method takes arguments as an array.

The apply() method is very handy if you want to use an array instead of an argument list.

The apply() Method with Arguments

The apply() method accepts arguments in an array.

					 
        
          const person = {
            fullName: function(city, country) {
              return this.firstName + " " + this.lastName + "," + city + "," + country;
            }
          }

          const person1 = {
            firstName:"John",
            lastName: "Doe"
          }

          person.fullName.apply(person1, ["Oslo", "Norway"]);
        
      
Simulate a Max Method on Arrays

You can find the largest number (in a list of numbers) using the Math.max() method.

Since JavaScript arrays do not have a max() method, you can apply the Math.max() method instead.

					 
        
          Math.max(1,2,3); // Will return 3

          Math.max.apply(null, [1,2,3]); // Will also return 3

          // The first argument (null) does not matter. It is not used.
          Math.max.apply(Math, [1,2,3]); // Will also return 3
          Math.max.apply(0, [1,2,3]); // Will also return 3
          Math.max.apply("", [1,2,3]); // Will also return 3
        
      
JavaScript Strict Mode

In JavaScript strict mode, if the first argument of the apply() method is not an object, it becomes the owner (object) of the invoked function. In "non-strict" mode, it becomes the global object.

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved