-1

Let's say I have a function myFunction which in it's body uses results of other function otherFunction and those results are constant per every invocation.

function myFunction() {
  doSomething(otherFunction());
}

In the past I used IIFE-s to invoke otherFunction only once and so optimize the code:

var myFunction = (function() {
  let otherFunctionResult = otherFunction();

  return function() {
    doSomething(otherFunctionResult);
  };
}());

I wonder if ES6 const keyword would achieve the same result without using IIFE:

function myFunction() {
  const OTHER_FUNCTION_RESULT = otherFunction();
  doSomething(OTHER_FUNCTION_RESULT);
}

Can I expect const to be optimized so that otherFunction is invoked only once? That would greatly simplify the code.

Robert Kusznier
  • 6,471
  • 9
  • 50
  • 71

2 Answers2

1

The fact that OTHER_FUNCTION_RESULT is declared as const doesn't mean it's only ever called once:

function callOften(){
  const test = init(); // This is a `const`, but does it get called more often?
}

function init(){
  console.log('Init Called');
  return 1;
}

callOften();
callOften();
callOften();

Basically, your IIFE is one way to do what you want.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
1

Yes, you don't need IIFEs any more in ES6. However, you seem to confuse const with what static does in other languages. You still need to initialise it outside of the function if you want to invoke otherFunction only once. It would look like this:

var myFunction;
{ // block scope!
  let otherFunctionResult = otherFunction(); // `const` works the same here

  myFunction = function() {
    doSomething(otherFunctionResult);
  };
}

Admittedly, an IIFE is still nicer to read if your module has a result (here: the function) that is supposed to be stored in a non-local variable.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375