# 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' && document.getElementsByTagName('html')[0].hasAttribute('dir')) {
document.getElementsByTagName('html')[0].removeAttribute('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));
}
}


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?

• Lack of context: Please update your question with the HTML being used. Sep 4 '18 at 14:48
• @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 Sep 4 '18 at 14:53
• document.getElementById tends to imply that HTML is being used. Sep 4 '18 at 14:55
• @FreezePhoenix for that please read my question and scroll down to see my own answer to my question stackoverflow.com/questions/52154725/… Sep 4 '18 at 15:09
• I see your point, but at the minimum you should explain the structure of the HTML in your question. Sep 4 '18 at 15:18

localStorage.setItem('lang', language);

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