Search code examples
javascriptvue.jsarrow-functions

Can sombody explain me this arrow function in javascript?


here is the code:

const createI18n = (config) => ({
    locale: ref(config.locale),
    messages: config.messages,
    $t(key) {
        return this.messages[this.locale.value][key]
    },
})

Is locale an object or a proprety of object?

I'm kind of new in javascript and i really struggling in understanding this arrow function.


Solution

  • To better understand what is going on here, you could take a look at a normal function equivalent:

        function createI18n(config){
            return {
               locale: ref(config.locale),
               messages: config.messages,
               $t(key) {
                  return this.messages[this.locale.value][key]
               }
            }
    }
    

    So basically you are returning an object from that arrow function. You are also using a shorthand version of an arrow function, which omitts the return keyword.

    So those two are equivalent to the one above as well

    const createI18n = (config) => ({
        locale: ref(config.locale),
        messages: config.messages,
        $t(key) {
            return this.messages[this.locale.value][key]
        },
    })
    
    const createI18n = (config) => {
    /* you could do some operations here, but not in the shorthand version */
    return {
        locale: ref(config.locale),
        messages: config.messages,
        $t(key) {
            return this.messages[this.locale.value][key]
        },
      }
    }
    

    It is just a more convenient kind to write the function.

    update: The result object would look like this:

    {
     locale: //some value,
     messages: //some other value,
     $t: // function
    }
    

    update 2: you could rewrite your function to observe the result in the console.

    const createI18n = (config) => {
    const result = {
         locale: ref(config.locale),
         messages: config.messages,
         $t(key) {
             return this.messages[this.locale.value][key]
         },
     }
     console.log(result);
     return result
    }