Language switcher, consulting browser's localStorage I'm using angular 6 and ngx-translate. This is my switch language function

  switchLanguage(language: string) {
    this.translate.use(language);
    if (language !== 'ar' &amp;&amp; document.getElementsByTagName('html')[0].hasAttribute('dir')) {
      document.getElementsByTagName('html')[0].removeAttribute('dir');
    } else if (language === 'ar' &amp;&amp; !document.getElementsByTagName('html')[0].hasAttribute('dir')) {
      document.getElementsByTagName('html')[0].setAttribute('dir', 'rtl');
    }
    // if this line worth it?
    if (language !== JSON.parse(localStorage.getItem('lang'))) {
    localStorage.setItem('lang', JSON.stringify(language));
    }
  }


I'm asking about this line in particular

if (language !== JSON.parse(localStorage.getItem('lang'))) 


If I don't use it, it means that if the language is english and you switch it to english, the localStorage is going to be updated. If I use it however, it means that, every time you switch a language, it's going to read  localstorage to check its value before updating.

Is the cost of just setting the language better than the cost of checking it first?

This method is getting called whenever you switch the language and in app.ts constructor, so basically on every page load. Is there a better way to do it?
The rewrite of LocalStorage is normal practice because of a rewrite time ~equal check time. 

You can change the code.

localStorage.setItem('lang', language);


By the way JSON.parse and  JSON.stringify is unnecessary actions in your code because language is already string.



I only considered the code associated with your the question.