[Vuejs]-Object is null while typeof is object?

2๐Ÿ‘

  let lang = this.$store.state.lang

  if(!lang){
    lang = 'nl'
  }
  if (name && typeof name === 'object') {
    if (typeof name[lang] === 'string' && name[lang]) { // <- null is not an object (evaluating 't[e]')
      return name[lang]
    }
    return name['nl'] ? name['nl'] : ''
  }
  return ''

1๐Ÿ‘

As other people have commented on your question, typeof null gives object on Javascript:

console.log(typeof null);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

The following table summarizes the possible return values of typeof (from MDN):

Type                                                    | Result
Undefined                                               | "undefined"
Null                                                    | "object" (see below)
Boolean                                                 | "boolean"
Number                                                  | "number"
String                                                  | "string"
Symbol (new in ECMAScript 2015)                         | "symbol"
Host object (provided by the JS environment)            | Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms) | "function"
Any other object                                        | "object"

Now, looking at your code, I believe it could be rearrange in this way:

let lang = this.$store.state.lang

if (!lang)
    lang = 'nl'

if (name && name[lang] && typeof name[lang] === 'string')
    return name[lang];

return '';

Note, there is no need for the next explicit check since you are defining default language to nl when it is not defined:

return name['nl'] ? name['nl'] : ''

Leave a comment