skip to Main Content

If I have the following code in Javascript:

import getTranslation from "some-library";
import getUserSettings from "some-other-library";

const getTranslatedLabel = () => {
  const translatedLabel = getTranslation("cheeseburger");
  const { enableTranslatedLabels } = getUserSettings();

  if (enableTranslatedLabels) {
     return translatedLabel;
  } else {
     return "";
  }
}

Is a javascript engine like V8 smart enough to only execute the getTranslation function if enableTranslatedLabels is true?

2

Answers


  1. This has nothing to do with V8 and more to do with your business logic.

    You need to rearrange your code so you will execute the function only when enabled.

    import getTranslation from "some-library";
    import getUserSettings from "some-other-library";
    
    const getTranslatedLabel = () => {
    
      const { enableTranslatedLabels } = getUserSettings();
    
      //if not enabled, we will not executed getTranslation
      if( !enableTranslatedLabels ){
         return "";
      }
    
      //this will be executed and value returned because it is enabled.
      return getTranslation("cheeseburger");
    
    }
    
    Login or Signup to reply.
  2. As other say thats requieres your "logic condition",
    because JS is a interpreted language.

    That’s how you can operate with special combination of
    using && (Short-Circuit) and || (Short-Circuit)

    import getTranslation from "some-library";
    import getUserSettings from "some-other-library";
    
    const getTranslatedLabel = () => {
      return (
              (
                getUserSettings().enableTranslatedLabels &&
                getTranslation('cheeseburger')
              ) 
             || ''
          );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search