top of page
Search

A different way of looking at Javascript Functions

  • panthakiurmez
  • Apr 10, 2023
  • 2 min read

The traditional way of thinking about functions is that you declare a function and then add code inside it. But the inverse thinking is equally powerful and useful: take any arbitrary section of code you’ve written and wrap a function declaration around it, which in effect “hides” the code.

The practical result is to create a scope bubble around the code in question, which means that any declarations (variable or function) in that code will now be tied to the scope of the new wrapping function, rather than the previously enclosing scope. In other words, you can “hide” variables and functions by enclosing them in the scope of a function.


Why would “hiding” variables and functions be a useful technique?


There are a variety of reasons motivating this scope-based hiding. They tend to arise from the software design principle Principle of Least Privilege, also sometimes called Least Authority or Least Exposure. This principle states that in the design of software, such as the API for a module/object, you should expose only what is minimally necessary, and “hide” everything else. This principle extends to the choice of which scope to contain variables and functions. If all variables and functions were in the global scope, they would of course be accessible to any nested scope. But this would violate the “Least…” principle in that you are (likely) exposing many variables or functions that you should otherwise keep private, as proper use of the code would discourage access to those variables/functions.

For example:



function doSomething(a) {
  b = a + doSomethingElse( a * 2 );
  console.log( b * 3 ); 
}  function doSomethingElse(a) {  
  return a - 1;  
}  var b;  
  doSomething( 2 ); // 15

In this snippet, the b variable and the doSomethingElse(..) function are likely “private” details of how doSomething(..) does its job. Giving the enclosing scope “access” to b and doSomethingElse(..) is not only unnecessary but also possibly “dangerous,” in that they may be used in unexpected ways, intentionally or not, and this may violate precondition assumptions of doSomething(..). A more “proper” design would hide these private details inside the scope of doSomething(..), such as:


function doSomething(a) {
  function doSomethingElse(a) { 
  	 return a - 1;  
  }   var b;   
  b = a + doSomethingElse( a * 2 );   
  console.log( b * 3 ); 
} 	  
doSomething( 2 ); // 15

Now, b and doSomethingElse(..) are not accessible to any outside influence, instead controlled only by doSomething(..). The functionality and end result has not been affected, but the design keeps private details private, which is usually considered better software.

 
 
 

Comments


Post: Blog2_Post
bottom of page