Modern JavaScript
About Lesson

In this JavaScript lesson we are going to talk about JavaScript Static Functions, so static functions are defined in classes itself not on the prototype, it means that we can not call static functions on the object, but we can call it on the class name.

 

 

Now let’s create an example, you can see that we have static function in our class, you can not access to this static function using the class object.

 

 

 

You can access to that static function using the class name it self not the object.

 

 

 

JavaScript Static Functions Features

As we already mentioned that Static function are functions that are attached to a class rather than to an instance of class. these are some features of JavaScript static functions along with code examples:

 

  1. Static Function Declaration: You can define static function in class using static keyword before the function name.

In this example, the MathUtils class is defined with static functions add and multiply. static functions can be called on the class itself without creating an instance of the class.

 

 

  1. Use Case for Static Function: common use case for static functions is to create utility functions that are used throughout an application.

In this example StringUtils class is defined with static function truncate that truncates string to maximum length. static function can be called on the class itself to perform the truncation operation.

 

  1. Static Functions vs Instance Functions: Static functions are different from instance functions in that they are called on the class itself rather than on an instance of the class. Instance functions are called on an instance of the class and have access to instance specific properties and methods.

 

In conclusion we can say that static functions in JavaScript are useful feature that can help you organize and modularize your code. they can be used to create utility functions, perform calculations or perform other operations that do not require an instance of class.