eded eded - 23 days ago 7
Javascript Question

the use of javascript self invoke anonymous function

Please see the following code blocks. Which one is the best option? Basically they are all doing the same thing

Example 1

var otherVars1
var otherVars2
var otherVars3
var valid; // create a boolean variable
// some precondition to set valid to true or false
....

if (valid || someRegex.test(value)) {
...
}


Example 2

var otherVars1
var otherVars2
var otherVars3

// create a function that return a boolean
function isValid() {
...
return Boolean
}

if (isValid() || someRegex.test(value)) {
...
}


Example 3

var otherVars1
var otherVars2
var otherVars3

// use self-invoke anonymous function directly
if ((function() {
...
return Boolean })() || someRgex.test(value)) {
...
}


Comparing these three examples, I prefer to use self invoke anonymous function(example 3) for the following reasons


  • Does not need to create unnecessary vars and allocate memory (ex1: valid, ex2: isValid)

  • Keep code clean, piece by piece or module so that it is easy to manage and organize

  • Self contained so that the variable outside of self invoke anonymous function does not get polluted



Please correct me if I am wrong on any of the point above and tell me what is your preference and reason?

Answer

I would say you can go with the immediate invocation of function expressions but you can avoid using them inside the if and you could use as below.

This will avoid unnecessary global scope of variable declarations, functions etc.

(function() {
  var otherVars1
  var otherVars2
  var otherVars3
  var valid; // create a boolean variable
  // some precondition to set valid to true or false
  .... 

  if (valid || someRegex.test(value)) {
    ...
  }

})();