Search code examples
javascriptecmascript-6frontendstatic-methodses6-class

Difference between Static function declaration and the normal function declaration in Javascript?


There are many ways one can declare a function in javascript. One of the ways is declaring a class and a static function inside is as showed below.

class className {
 static fucntionName() {
 }
}

another way of is declaring is through the tradition javascript style as showed below.

function functionName() {
}

I would like to know the advantages/disadvantages of using either of the cases. Is there any specific use cases for the static methods, why declare a class(we know that in javascript there is no need to instantiate the class in order to access the static function). Why not just use the traditional way (the second case in the above example) of function declaration in all/any use case?

I would like to understand this is in detail.


Solution

  • A static method is callable from the class itself, as you already know.

    A non-static method is callable from an instance of the class, so you basically have to create an object before being able to access that method.

    For example, for a addNumbers(var a, var b) which does return a+b, is it really necessary to waste memory instantiating an object of the class just to add those 2 numbers? No, you just need the result and that's the whole point of having static.

    Using the first style allows you to group methods in a particular class (think of something like namespaces). Maybe you can define classes like Math and String, which both have the add method but implemented in a different way. Calling add() by itself would be confusing, but Math.add() and String.add() are not.

    The export style, on the other way, does a completely different thing. It allows you to use functions from another module.

    Think about this:

    first_module.js

    function cube(var x) {
        return x * x * x;
    }
    

    second_module.js

    import { cube } from 'first_module'; // <-- ERROR
    alert( cube(3) ); // <-- Undefined function
    

    But, if you declare first_module this way:

    export function cube(var x) {
        return x * x * x;
    }
    

    Then second_module will work fine.