Search code examples
javascriptglobal-variableshoisting

Push to array and convert to string


I need to pass a value as a string and not an array from inside an event listener to a global variable.

Currently when the page loads, I check for a cookie inside the event listener and pass that value ('de', 'es', 'en' etc) to an empty array. I don't know a better way to hoist this variable. I then use the array value for a widget setting. Obviously this is passing the value as an array IE ['de']. How do I pass the value to the array, then run a toString function and redeclare the variable?

const user_sel_lang = [];
 window.addEventListener('load', function () {
      var user_lang_c = Cookies.get('user_lang');
      user_sel_lang.push(user_lang_c);
  }, false);

window.adaSettings = {
    language: user_sel_lang,
    align: "left"
}

When I do something like this, and then console.log(settings)I get undefined for the language.

const user_sel_lang = [];
let user_sel_lang_string = user_sel_lang.toString();

window.addEventListener('load', function () {
    var user_lang_c = Cookies.get('user_lang');
    user_sel_lang.push(user_lang_c);
  }, false);

window.settings = {
    language:user_sel_lang_string,
    align:"left"
}

Solution

  • If there is no particular reason to get the cookie on load event, you can just run everything synchronously

    window.settings = {
        language: Cookies.get('user_lang'),
        align:"left"
    }
    

    If you absolutely need to update the user lang on load, then you could use a default value and run an update after the lang is updated

    const defaultLang = 'en';
    window.addEventListener('load', function () {
        var user_lang_c = Cookies.get('user_lang');
        window.settings.language = user_lang_c;
        // run some update code to take into account the new language
      }, false);
    
    window.settings = {
        language: defaultLang,
        align:"left"
    }
    

    Or you can wait for the language to be retrieved before initializing the app by wrapping everything in the on load callback:

    window.addEventListener('load', function () {
        var user_lang_c = Cookies.get('user_lang');
        window.settings = {
          language: user_lang_c,
          align:"left"
        }
        startApp();
      }, false);
    
    function startApp() {
      // put all your code here
    }