Why isn't my variable being assigned a value from a JavaScript function?

My JS snippet includes a function that retrieves customer interest data from a specified URL using basic authentication. When calling this function in my HTML file, I am encountering an issue where the expected value is displayed only in one of the alerts and not in the console log.

function fetchData(customerRef) {
  try {
    var customerInterest = "";
    var baseUrl = "https://test/";
    var url = baseUrl + customerRef;
    var username = "username";
    var password = "password";

    var request = new XMLHttpRequest();
    request.open("GET", url);
    request.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
    request.send();
    request.onload = () => {
      if (request.status == 200) {
        var guestJson = JSON.parse(request.response);
        var sessions = guestJson.sessions || [];
        var interest = sessions.filter(session => session.events)
          .flatMap(session => session.events)
          .filter(event => event.type === "SEARCH")
          .map(event => event.arbitraryData.interest)[0];
        customerInterest = interest;
        alert("---" + customerInterest);
      } else {
        console.log(`error ${request.status} ${request.statusText}`);
      }
    }
    alert(customerInterest);
    return customerInterest;
  } catch (error) {
    console.error(error);
  }
}

customerRef = "6a789727";
var interest1 = "";
interest1 = fetchData(customerRef);
console.log(interest1);

Answer №1

Not only will you receive an error, but it won't just be undefined.

Upon execution,

var test = "";
test = test()
console.log(test)

You will encounter

Uncaught TypeError: test is not a function

on line 2. This is because you assigned the value of test as a string ("") rather than a callable function.

For a proper solution, consider:

function greet() {
 return "Hi";
}
var test = "";
test = greet();
console.log(test);

When evaluated in the console, this will output

Hi
undefined

; the additional undefined arises from the return value of console.log();

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

What is the best approach for creating a NestJS application for production that includes all node_modules dependencies in the bundle?

When I use nest build or nest build --webpack, the dist folder does not contain all the required modules, resulting in an error when trying to run node main.js: Error: Cannot find module '@nestjs/core'. I have searched through the documentation ...

Encountering the error "TypeError: Unable to access property 'findAll' of undefined" when using Sequlize

Currently, I am in the process of developing a CRUD Application utilizing PostgreSQL, Sequelize, and Express. I have been referring to this specific tutorial as my guide. However, it appears that there might be an issue with either my model or database con ...

Learn the method to navigate back from a side menu-pushed page on Ionic framework

Currently working on developing an ionic app where I want to be able to push a page directly from my side menu. However, I have encountered an issue where once I navigate to the new page, I am unable to swipe back to the previous page and can only go back ...

Attempting to retrieve the _id property from a component within a Next.js application using Mongodb and Mongoose

I've recently started delving into mongodb and mongoose, and I'm encountering an issue while trying to access the id property (_id) using demo._id after utilizing getServerSideProps. Surprisingly, it seems to be functioning properly on my page lo ...

Patiently anticipating the completion of a jQuery animation

I am currently working on some jQuery code that handles toggling containers and buttons. The specific snippet of code I am focused on is the following: var id = $(this).data('id'); if ($('#container').is(':visible')) { $( ...

Using keys dynamically fetched from a JSON array file to enhance d3js functionality

I am looking to dynamically retrieve keys from an external JSON array and utilize them in d3js functions to create bar charts. Below is the JSON code provided: [ { "Interns": 5, "Projects": 10, "Time":"Jan" }, { "Interns": 16, "Pr ...

Transforming JSON data into comma-delimited values (with thousands separators) using Angular 5 and ES6 syntax

Is there a more elegant method to convert a JSON response into comma-separated numbers for displaying currency purposes? Here is the code I have currently: let data = { "business":{ "trasactionTableData":[ { ...

Express.js - Struggling with Setting the Content-Type Response Header

While using Express.js, I am facing an issue with setting the Content-Type header. Even after specifying it as text/html, the response is being sent with application/octet-stream. Below is the snippet of my code: const express = require("express" ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...

Guide on destructuring an object to update MySQL with corresponding keys and values

For my project, I am transferring data from a react frontend to an express backend using axios: axios.post('http://localhost/api', {example1: true, example2: false}); Once the data reaches the backend, I am updating a MySQL database with the rec ...

Verifying the presence of a redundant username

Currently, I am developing a registration page for my mobile application where I need to ensure that the usernames entered by users are not duplicates. In order to achieve this, I have implemented a button on the page that allows users to check the availab ...

How can you simulate a node-cron job using jest?

I am currently working on a node application that is built with Typescript and includes a cron job. The cron job is triggered when the server starts. I have been writing unit tests for this application, but I am facing difficulties in mocking the node-cro ...

Incorporate adjustable div heights for dynamically toggling classes on various DOM elements

One of the challenges in developing a chat widget is creating an editable div for users to input text. In order to maintain the design integrity, the box needs to be fixed to the bottom. An essential requirement is to have javascript detect resizing as us ...

How to showcase a single JSON object using AngularJS

When I retrieve news with a specific id from my REST API, using ng-repeat to display all news works fine. However, when I try to display a single object, this method does not work. My route code: .when('/displaynews/:id',{ templateUrl: &apo ...

Retrieve the access ID from the conn.query result

When I run a SQL query, I need to extract the primary key (id) of the event returned so I can use it in another SQL query. However, attempting to access it using result.insertId returns null for the event object. Even logging result.insertId only outputs ...

Is it possible to arrange JSON Objects vertically on a webpage using tables, flexboxes, divs, and Javascript?

Within my JSON data, I have multiple products defined. My goal is to loop through this JSON and display these products side by side on a web page for easy comparison. Initially, I envision structuring them in columns and then rows: https://i.sstatic.net/K ...

The documentation for the 4-11.4 version of Material UI cannot be found anywhere

After the release of MUI v5.0.0-rc.1, it appears that all documentation pages for version 4, except for v4.12.3, have vanished. https://mui.com/versions/ Furthermore, (currently not accessible) Is there a way to access previous versions' document ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

Storing keys and multiple maps with React applications

Having a multiple array with an option set created, everything is functioning correctly const groups1 = OrgServices.reduce((all, cur) => ((all[cur.grouptype] ??= []).push(...cur.servicetype), all), {}); const output1 = Object.entries(groups1).map ...

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...