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

"Integrating multiple partials with templateUrl in AngularJS: A step-by-step

Is there a way to merge partial views using the templateUrl attribute in an AngularJS directive? Imagine having a directive like this: .directive('combinePartials', function () { var mainPartial = "mainpartial.html", var template2 = "pa ...

"Exploring the process of integrating a new language into the vuejs3-datepicker feature

Hey there, I'm wondering if anyone knows how to integrate a new custom language into vuejs3-datepicker? I checked out the documentation at https://www.npmjs.com/package/vuejs3-datepicker?activeTab=readme, but it seems like you need to add the new lan ...

Comprehending the principles of Vue components and navigation paths

I have embarked on the journey of mastering the art of website development, utilizing a Vue frontend in conjunction with an Express REST backend. One of the new routes I created looks like this: /path/to/vue-client/routes/index.js import Vue from ' ...

Video background mute feature malfunctioning

I've searched through numerous resources and reviewed various solutions for this issue, yet I still haven't been able to figure it out. Could someone please guide me on how to mute my youtube embedded video? P.s. I am a beginner when it comes to ...

What is the best method for looping through a JavaScript object in cases where the value itself is an object?

Updated query. Thanks to @WiktorZychla for sparking my Monday morning thoughts on recursion. The revised code is functioning correctly now. Assuming I have a dummy object structured like this: const dummy = { a: 1, b: 2, c: { d: 3, ...

What steps do I need to take to set up CORS properly in order to prevent errors with

I encountered the following error message: "Access to XMLHttpRequest at 'api-domain' from origin 'website-domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HT ...

When working with angular.js and angular-sanitize.js, the src attribute is removed from JSON HTML data

I'm new to Angular and I'm really enjoying learning how to work with it. Currently, I have a simple JSON file that contains text structured like this: "gettingstarted":{ "title":"Getting Started", "content":"<img ng-src='i ...

Guide on configuring and executing AngularJS Protractor tests using Jenkins

I am encountering an error with the following configuration: ERROR registration capabilities Capabilities [{platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=}] does not match the current platform LINUX 18:17:05.892 INFO ...

What is the best way to assign a URL to an image source using a JavaScript variable?

I am working on a script that displays different image URLs based on the time of day using an if-else statement. I want to dynamically load these images in an img src tag so that a different picture is loaded for each time of day. I have defined variables ...

Having trouble finding module: Unable to locate 'fs' - yet another hurdle with NextJS

Trying to access a JSON file located one directory above the NextJS application directory can be tricky. In a standard JavaScript setup, you might use the following code: var fs = require('fs'); var data = JSON.parse(fs.readFileSync(directory_pat ...

Initiate an Ajax call to pre-fetch video content

I've been attempting to download a video from my own source and display a loading message while it's being downloaded. Once the download is complete, I want to hide the loading icon and have the video ready for playback. My issue lies in gettin ...

Having an issue with my Vue page where it is attempting to send a request twice. My tech stack includes inertia, Laravel, and

<template> <app-layout title="Dashboard"> <template #header> <h2 class="h4 font-weight-bold">Create</h2> </template> <div class="container mt-5 text-gray-300"> ...

Verifying that a parameter is sent to a function triggering an event in VueJS

One of the components in my codebase is designed to render buttons based on an array of objects as a prop. When these buttons are clicked, an object with specific values is passed to the event handler. Here's an example of how the object looks: { boxe ...

Application of id missing on all buttons in Bootstrap tour template

I'm having an issue with applying a new id to the next button in a Bootstrap tour template. I added the id to the button, but it only seems to work for the first stage and not the subsequent ones. Can anyone provide insight into why this might be happ ...

Feeling uncertain about Node, NPM, Bower, and how to set them up for Bootstrap?

Looking to expand my knowledge in web development, I have a solid understanding of HTML, JS, CSS, and server-side programming. However, the concepts of Nodejs, npm, and Bower are still unclear to me. In order to begin a new project, I created a designated ...

Exploring Node.js with the power of EcmaScript through Javascript Mapping

I am currently using Map in NodeJS version 0.10.36 with the harmony flag enabled. While I am able to create a map, set and retrieve data successfully, I am facing issues with other methods such as size, keys(), entries(), and forEach as they are returning ...

how can I enable pass-through functionality in express middleware?

Currently, I have a POST API endpoint named /users which is used to retrieve the list of users. The reason behind using POST instead of GET is because the request body can be quite large and it may not fit in the URL for a GET request. In this scenario, i ...

Create a visual representation of an image by sketching a detailed line profile using HTML5's

I am attempting to create an intensity profile for an image, using the x-axis as the line's length on the image and the y-axis as the intensity values along the length of the line. How can I achieve this on an HTML5 canvas? I have tried the code below ...

What is the process for retrieving data from a javascript file that was submitted through a form?

Can you help me with an issue I'm having with this code snippet? <form action="main.js"> <input type="text" required="required" pattern="[a-zA-Z]+" /> <input type="submit" value="Submit" /> </form> After c ...

Utilize the string module from a JavaScript file in your React or Next.js project

Within my project structure, I have a file named "test.js" located in the "/constants" directory. The content of this file is as follows: const test = "test!" export default test In another part of my project, specifically within the "/pages" folder, I w ...