I'm using angular 6 and ngx-translate. This is my switch language function

  switchLanguage(language: string) {
    if (language !== 'ar' && document.getElementsByTagName('html')[0].hasAttribute('dir')) {
    } else if (language === 'ar' && !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?

  • \$\begingroup\$ Lack of context: Please update your question with the HTML being used. \$\endgroup\$ Sep 4, 2018 at 14:48
  • \$\begingroup\$ @FreezePhoenix what html? I don't use html, this all i have, I don't understand your question. What would html have to do with localstorage? Maybe I misunderstood your question \$\endgroup\$
    – Lynob
    Sep 4, 2018 at 14:53
  • \$\begingroup\$ document.getElementById tends to imply that HTML is being used. \$\endgroup\$ Sep 4, 2018 at 14:55
  • \$\begingroup\$ @FreezePhoenix for that please read my question and scroll down to see my own answer to my question stackoverflow.com/questions/52154725/… \$\endgroup\$
    – Lynob
    Sep 4, 2018 at 15:09
  • 1
    \$\begingroup\$ I see your point, but at the minimum you should explain the structure of the HTML in your question. \$\endgroup\$ Sep 4, 2018 at 15:18

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.