Search code examples
javascriptoptimizationprivatereadability

Is there a way to avoid encapsulating javascript in parenthesis yet still get the benefits?


Lately, I've noticed javascript convention has been shifting. Now, wherever I look, I see other developers using javascript are wrapping their functions in parenthesis to make it private (or something like that I'm not sure, javascript is a secondary language for me). For example...

(function something()
    { // something happens here 
    })();

As stuff (especially additional functions) gets nested, this hurts code readability, and is really making javascript ugly and look more and more like the nightmares of programming in LISP(how it got it's nickname "Lots of Idiotic Single Parentheses). I don't care if I have to type out a full word (or even a couple words) to get the same effect. Is there a good alternative to encapsulating in parentheses to make a function private and get the other benefits of the parenthetical encapsulation?

Edit: Apparently I misunderstood the point of the outside surrounding parenthesis that I'm questioning. Which makes me more confused about their purpose, actually.


Solution

    • You can define regular function and call it when you need it

    Example

    var myObject = {
        something: function() {
        },
    
        somethingElse: function() {
        }
    };
    
    myObject.something();
    
    • ES6/ES2015 has now modules support

      //------ lib.js ------
      export const sqrt = Math.sqrt;
      export function square(x) {
          return x * x;
      }
      
      export function diag(x, y) {
          return sqrt(square(x) + square(y));
      }
      
      //------ main.js ------
      import { square, diag } from 'lib';
      console.log(square(11)); // 121
      console.log(diag(4, 3)); // 5
      

    You can read more about modules here