Conditionally defining variables in JavaScript only if they are currently undefined

I have been working on extracting two keywords from a URL in the following format:

localhost:3000/"charactername"/"realmname"

My goal is to extract "charactername" and "realmname" and assign them to variables.

Here is the code snippet I am using:

var charactername = req.url.split("/")[1];
console.log(charactername);
var realmname  = req.url.split("/")[2];
console.log(realmname);

Initially, everything works smoothly. However, I noticed that when a request is made for a "favicon.ico", my variables become undefined due to a new request URL being generated. To address this issue, I tried wrapping the code snippet in an if statement like this:

if(req.url !== '/favicon.ico'){ 
var charactername = req.url.split("/")[1];
console.log(charactername);
var realmname  = req.url.split("/")[2];
console.log(realmname);
}

Although the console logs show that the variables are correctly set to their values without being undefined, as the next part of the code executes:

if(charactername.length > 0){
            res.writeHead(200, {'Content-Type': 'text/html'});
            renderer.view("header", {}, res);

            //get json from battle.net
            var characterProfile = new Profile(charactername, realmname);

            //on "end"
            characterProfile.on("end", function(profileJSON){
                //Show profile
                //Store values we need
                var values = {
                    avatarURL: profileJSON.thumbnail,
                    charactername: profileJSON.name,
                    realmname: profileJSON.realm,
                    level: profileJSON.level
                }
                //Simple response
                renderer.view("profile", values, res);
                renderer.view("footer", {}, res);
                res.end();
            });

An error occurs stating that it cannot read property length of undefined. This suggests that the variables somehow become undefined regardless. Can someone provide guidance on how to tackle this issue?

Answer №1

if(variable === undefined){
  //perform an action
}

This condition is verifying if the variable is undefined, but it would be beneficial to investigate the root cause of the error.

Answer №2

When there is a valid charactername with length greater than zero:

...

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 there a way to circumvent the mouse up event?

I want to create a feature where when a user clicks down, something specific occurs. The sequence of events includes: An action taking place (which is not the focus here). Triggering a mouse up event. Implemented with: angular, html, css. Excludes: jQue ...

Javascript keycode used to target the element when a key is pressed

In my current project, I am utilizing a code snippet to attach a KeyDown event handler to any element within the HTML form. for(var i=0;i<ele.length;i++) { ele[i].onkeydown = function() { alert('onkeydown'); } } I am ...

Guide on displaying API data within nested fields in ReactJS

import axios from 'axios' import { CART_ADD_ITEM } from '../constants/cartConstants' export const addToCart = (uid, qty) => async (dispatch, getState) => { const { data } = await axios.get(`/api/v1/`) dispatch({ ...

Exploring Node's Configuration File Reading Process

Trying my best to provide all the details for my question. Being a newbie to NodeJS, I appreciate your kind guidance :D In the process of developing an application in Node, focusing on enabling users to view stats regarding their Plex Media Libraries. The ...

What is the best way to preserve the allocated space in the DOM while utilizing CSS display:none?

I have explored the functionalities of display:none and visibility:hidden. However, I need to utilize display:none for a specific reason while still preserving the element's allocated space in the DOM to prevent any impact on adjacent elements. Is thi ...

Connecting Vue component data to external state sources

I am facing a challenge with integrating a Vue component into a large legacy system that is not based on Vue. This component retrieves data through AJAX requests and displays information based on an array of database record IDs, typically passed at page lo ...

I aim to display interconnected information from various APIs in a cohesive manner

I am working with two APIs: component.ts ngOnInit(): void { this.getQueryCountriesList().subscribe(arg => { this.countryDatas = arg; }); this.getQueryNights().subscribe(obj => { this.nightDatas = obj; }); ...

Using MaterialUI to create a GridListTile with two IconButtons

I'm working with a GridListTile and trying to add a second button, but I'm having trouble getting both buttons to display. Even though I've attempted to include two ActionIcons, only one of them is showing up. Here's the code snippet: ...

Tips for personalizing react-show-more text length with Material-UI Icons

In my SharePoint Framework webpart using React, I am currently utilizing the show more text controller. However, I am interested in replacing the "Show More" and "Show Less" string links with the ExpandMore and ExpandLess Material UI icons. Is there a way ...

The initialization of the Angular service is experiencing issues

I have a service in place that checks user authentication to determine whether to redirect them to the login page or the logged-in area. services.js: var servicesModule = angular.module('servicesModule', []); servicesModule.service('login ...

When using @mouseover, it is not possible to modify a variable's value

The hover event is not functioning properly in this Vue component. Although I was able to call a function on hover successfully, I encountered issues when trying to change the hover variable directly. <template> <div @mouseover="hover = t ...

Incorporating a dynamic fill effect into an SVG pie chart

I am looking to animate a pie chart with a variable value that is unknown upon loading. Assuming I fetch the value promptly and convert it into a rounded percentage : var percentage = Math.round(sum * 100 / total); Next, I place this value here : <di ...

Fetching Unicode block specials using axios in getStaticProps with Next.js

Click here to view the code and data results My attempt using the fetch method was successful, but I encountered issues when trying to use 'axios' ...

Cutting imagery to create a new design element

https://i.sstatic.net/IAh0h.jpg There is an image above with 6 gears (circles with pointy edges). My goal is to separate them into individual pictures and, on each picture's hover, have a relevant line with text appear. How can I achieve this? The a ...

What is the best way to retrieve a specific object from a JSON file using a Get request in a Node.js application?

My focus is on optimizing an API, which is why I'm working with only the data that's essential for my analysis. I've set up a route to extract specific objects, but I'm only interested in four of them: account_manager, fronter, closer, ...

Exploring an unusual HTML structure using Python's Beautiful Soup and urllib for web scraping

While extracting data may not be a challenge, the real issue lies in locating it. My focus is on scraping football data from a website that presents statistics either for all years or for specific seasons. However, despite selecting a particular season, ...

When invoking Javascript, its behavior may vary depending on whether it is being called from a custom

Currently, I am in the process of implementing versioning capabilities to a custom entity called MFAs. However, I have encountered a peculiar issue. The problem arises from having a JavaScript web resource that is being invoked from two different locations ...

React app's compilation is failing due to non-compliant ES5 code generation of the abab module, resulting in errors on IE

Can anyone explain why a create-react-app project using TypeScript and configured to generate ES5 code is not functioning on IE11 due to the "atob" function from the 'abab' package not being compiled into ES5 compliant code? module.exports = { ...

Changing the color of a progress bar in Bootstrap based on a specific percentage level

var elem = document.getElementById("progress-bar"); var progress = 75; elem.style.width = 80 + '%'; if (progress > 80) { elem.style.background = "red"; } #myProgress { height: 5px; } #progress-bar { w ...

unable to render the JavaScript code

Utilizing JavaScript post an ajax request to showcase the data in a div using new JS content. The example code is provided below: //ajax call from a.jsp var goUrl = "/testMethod/getTestMethod; var httpRequest=null; var refreshCont ...