Is it possible for an object to be null even when its type is object

There's an issue that I can't seem to replicate. Personally, I'm not experiencing any errors but bugsnag reports that some users are encountering them. Take a look at snippet line 6 for more information.

  let lang = this.$store.state.lang

  if(!lang){
    lang = 'nl'
  }
  if (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 ''

Answer №1

  const currentLanguage = this.$store.state.lang;

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

Answer №2

Many have pointed out that when you use typeof null in Javascript, the result is object:

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

A summary table of possible return values for typeof (sourced from MDN) is provided below:

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"

Upon reviewing your code, it seems like a reorganization could enhance readability:

let lang = this.$store.state.lang

if (!lang)
    lang = 'nl'

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

return '';

The explicit check for default language assignment is redundant in your case since you've already set it to nl if not defined:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to implement sandboxing for Node.js modules?

I've been diving into the world of Node.js and I have this exciting idea to create a cutting-edge MUD (online text-based game) using it. Traditionally, MUD games have predefined commands, skills, and spells that players can use to navigate through var ...

Adding elements to my state array - Utilizing Nextjs/React/Javascript

After fetching data from 2 different APIs that each return an object, I have stored them in separate states. Now, I want to merge these two objects into a single state that contains both of them as an array. However, when I try to do this, the second obj ...

Error encountered while attempting to load background images from .json dataset

Currently, I am fetching data from a .json file and utilizing a v-for to loop through each object and generate a card for them individually. A strange issue has arisen that is leaving me puzzled: Upon refreshing the page, the background-size COVER no l ...

The issue arises when trying to use qtip2 in JavaScript upon page initialization

I successfully created a heatmap using JavaScript, utilizing a table with varying colors based on the displayed values' thresholds. To enhance user experience, I wanted to implement a popup window that shows additional information when hovering over a ...

Issue with the string formatting in Vue.js is causing unexpected behavior

Hi there, I'm currently working on dynamically styling a div in VueJs and running into an issue with the this.currentProgressLevel not being applied to the width property within the currentStyle object. I've attached a screenshot of the code I&ap ...

Matching request parameters with a JSON object using node.js and express framework

After uncommenting the lines, the code runs smoothly. However, whenever I enable the 'else' statement, I consistently receive a 'not found' message even when there is a match between req.params.code and data.airports[i].code. var exp ...

Leveraging shadow components with the Next.js pages directory

I am facing an issue with getting a simple shadcn button to work because I am unable to import the button. Although I am using nextjs 13, I am still utilizing the pages directory. Below is the process of how I installed shadcn. Here is the installation co ...

The integration of Vue JS is not displaying properly in an Electron application

My electron app is loading Vue JS 2 from my local machine, but when I attach my el to an element, it completely empties the element and replaces its contents with a Vue JS comment. What could be causing this issue? index.html <!DOCTYPE html> <htm ...

Is there a way to transfer multiple functions using a single context?

Having created individual contexts for my functions, I now seek to optimize them by consolidating all functions into a single context provider. The three functions that handle cart options are: handleAddProduct handleRemoveProduct handleC ...

JavaScript - Issue with For Loop when Finding Symmetric Difference

Here is my solution to a coding challenge on FreeCodeCamp called "Symmetric Difference." I'm puzzled as to why my code is returning 2, 3, 4, 6 instead of the expected 2, 3, 4, 6, 7. function sym(args) { args = Array.from(arguments); var new ...

Encountered a snag with submitting data via AJAX: received an error message stating

I created this custom script for a contact form on my website, and it seems to be working fine. However, I'm encountering an issue where instead of storing the data in my database, all I get is [object HTMLCollection]. Can someone please explain wh ...

How can I optimize the performance of JS-heavy pages on mobile devices?

As a website owner, I strive to optimize the performance of my site on mobile devices without the need for a separate "mobile-friendly" version or replacing large sections of code. With around 100K of JS code, including jQuery, I am determined to enhance b ...

Angular2 allows you to create pipes that can filter multiple values from JSON data

My program deals with an array of nested json objects that are structured as follows: [{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}] I am looking to implement a pipe that can filter out objects b ...

The `vue-select` npm package is experiencing issues with the onChange event functionality and is not working

I am currently utilizing [email protected]. By the way, I am wondering how to trigger the @change event when selecting another option? This is the existing codebase: <v-select v-model="selected" :options="['Vue.js','React&apos ...

How to Convert Irregular Timestamps in Node.js?

Currently, I am utilizing an API to retrieve information from Google News and proceed to save the data in Firestore. The challenge lies in the fact that the API delivers timestamps in various formats which are not uniform. For example: "1 Day Ago", "June ...

Utilize the HTML img tag in conjunction with AngularJS and Ionic to showcase dynamic images

Currently, I am working on a hybrid mobile app using ionic and Angularjs. I am facing an issue with displaying images through the img html tag in my app. The main layout of my page includes a carousel at the top that displays images and a list containing s ...

Generating a dynamic method for uploading multiple files

Is there a way to dynamically generate multiple upload forms upon clicking a button? I currently have code that allows for uploading one file, but I would like to be able to add additional forms for each file. In other words, if I need to upload 7 files, I ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

Managing large datasets effectively in NestJS using fast-csv

Currently leveraging NestJS v9, fast-csv v4, and BigQuery for my project. Controller (CSV Upload): @Post('upload') @ApiOperation({ description: 'Upload CSV File' }) @ApiConsumes('multipart/form-data') ... // Code shorten ...

Task failed: NativeScript encountered an error while attempting to merge dex archives

Encountered an error while developing an NS + Vue application - Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. > com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives ...