JavaScript: The variable `scopes` is declared

I'm completely new to JavaScript. Can anyone help me understand why this code isn't working, and what changes I need to make to fix it?

function getResults(keywords) {

        foo.foo = function() {
               var bar = foo.getSomeText; // Contains "blabla"
        };

        return bar;

    }

    // Global scope

    alert(bar); // Does nothing

Edit (apologies for the lack of information):

The issue is that I am trying to retrieve text from an XHR request and I need to use a function to handle the onreadystatechange event. Here is the original code:

function getResults(keywords) {
     // Make a request and get results

    var xhr = new XMLHttpRequest();
    xhr.open('GET', './autoc.php?s='+ encodeURIComponent(keywords));

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
           var response = xhr.responseText;
          var test = response.split('|');

        }
    };

    xhr.send(null);

    return test;

}

var hum = getResults('test');
console.log(hum);

Answer №1

This solution should do the trick.

let result;
const data = {content: 'example'};

function fetchResults(searchTerm) {

    data.response = (function() {
        return result = data.content; // Contains "example"
    })();

    return result;

}

// Global scope
result = fetchResults('hello');

console.log(result); // Nothing will happen​​​​​​​​​​​​​​​

JSFiddle Demo

  • Your original code may not work due to a syntax error since 'result' is not declared.
  • 'data' is an object here and also needs to be initialized before use.
  • fetchResults returns 'result', which can only be accessed after executing the function and assigning it to a global variable.

UPDATE

AJAX calls are asynchronous, so attempting to retrieve the value from the function that is being set in the callback will not work properly. Since the request is asynchronous, the function has already returned before the callback is executed. Therefore, the 'test' variable will always be undefined in this scenario.

Answer №2

foo.foo = function() {
    var example = foo.retrieveText; // Contains "blahblah"
};
return example;

Despite the absence of declaration for foo, the variable example is defined within a function and therefore has local scope in JavaScript. It cannot be accessed outside of this function, making it impossible to return it as attempted here.

If you wish to return example, it must be declared outside of the function:

var example = foo.retrieveText; // Contains "blahblah"
foo.foo = function() {

};
return example;

Answer №3

In JavaScript, the extent of a variable is quite straightforward. It falls into one of two categories:

  • The function in which it is initially declared
  • The global scope (referred to as window in a browser) if it is not declared within a specific function

Answer №4

The location where a variable is declared determines its scope. If you declare a variable inside the script tag directly, as opposed to within a method within the script tag block, it will become a global variable.

It seems unclear what your intention is with the code snippet provided, especially because the first "foo" in "foo.foo" is not defined. You may want to consider using this alternative approach:

<script type="text/javascript">
var foo = {} // create an empty global object named 'foo'

foo.foo = function() {
    var bar = "some random text";

//// additional code goes here

return bar;

}

var myBar = foo.foo(); // retrieve text from the method. Remember that the method call should come after the method definition
alert(myBar);
</script>

Learning Javascript can be enjoyable and straightforward. I recommend exploring introductory texts and studying code examples for better understanding.

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

Creating a new JSON by extracting a specific branch or node from an existing JSON data

I have a Nuki Smartlock and when I make two API calls to the Nuki Bridge, I receive JSON responses. I want to apply the same logic to both responses: When requesting for current states, the JSON looks like this: [{ "deviceType": 0, "nuk ...

Guide to using get() and res.sendFile() function to redirect webpages

Why is the page not redirecting properly? In my index.html file, I have this script: $.get( "/loginPage", function( data ) {}); The purpose of this script is to check if a user is logged in. If they are, it should redirect them to the lobbyPage. This is ...

Guide to setting a dynamic print style without affecting the screen media

In my report, there is a details section below. The screen provides instructions to view the details with a button that toggles the list's visibility. When printing the report, I only want the instructions to show if the list is visible. If the list ...

Enhancing Vue.js Scripts with Laravel Localization Language-Strings

Within my vue.js script, I have successfully implemented a sweetalert using two Laravel localization language strings. Now, I am attempting to utilize the same language strings as data properties in another vue.js component script. The issue arises when t ...

Adjust the Highcharts semi-pie design by eliminating the gap between the pie and the legend

I'm having trouble adjusting the spacing between the bottom of a semi circle donut chart in Highcharts and the legend below it. Despite my efforts, I have not been successful in reducing this gap. Here is the basic chart I am currently working on: h ...

Exploring methods for monitoring page transitions in Next.js

Looking to repurpose a menu I created in react using react-router-dom for use in nextjs. My objective is to update the menu state to 'false' and change the menuName to 'menu' upon clicking on a link within the menu. Implemented a useEf ...

Encountering a 404 error while using THREE.ImageUtils.loadTexture in three.js

My first attempt at using three.js involves loading a 3D model, but I'm encountering an issue with texture loading. loader.load('models/asteroid_OBJ/asteroid OBJ.js', function (geometry, materials) { var material = new THREE.MeshLambertM ...

Ways to retrieve files that are not located in the public directory in Next.js

I'm currently working on a project using Next.js and storing files in the root directory under /uploads/qr/myimage.png. How can I access this file within the project? I attempted to create a route /api/getImg/route.js dedicated to serving image files, ...

Tips for retrieving the selected item from Material-UI DropDownMenu

Hello fellow StackOverFlow users, I am new here so please be patient with me In my React app, I am using Material-UI's DropDownMenu to collect information from users. However, the issue I'm facing is that the value being pushed to state is an in ...

Sending a user to an external website through an XML response

In my current project, I am utilizing jQuery to fetch a PHP file. The PHP file executes a cURL request to an external website in order to obtain information for a payment request. The external site responds with XML data structured as follows: <Request ...

Type inference in TypeScript with transitivity

Consider this code snippet for illustration: function foo(t: "number"): number function foo(t: "string"): string function foo(t: "boolean"): boolean function foo(t: "number" | "string ...

Can you point me to the location where the 'req' parameter is specified?

I've been exploring a new authentication approach detailed in this article. One issue I'm encountering is locating where the req parameter is declared in the snippet below. It seems like my code won't compile because this parameter isn&apos ...

I'm perplexed as to why my JavaScript code isn't successfully adding data to my database

Recently, I delved into the world of NodeJS and Express. My goal was to utilize Node and Express along with MongoDB to establish a server and APIs for adding data to the database. Specifically, I aimed to write the code in ESmodules syntax for JavaScript. ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Enhancing ReactJS functionality by incorporating custom logic prior to resolving promises

In one of my components, there is a function as follows: this.props.firebase.getDropSites("123456").then(data => { console.log(data); }); This function in turn calls the following method from my utilities class: getDropSites(dropSiteId) { return th ...

Encountering an error while trying to run a Next.js application on Linux Mint

View the error screenshot After creating a new Next.js app with npx create-next-app, I ran npm run dev and encountered the following error message ...

What is the best way to extract the date January 1, 1970 from a datepicker?

Currently, I am utilizing a datepicker along with a function that converts dates from dd-mm-yyyy to yyyy-mm-dd format. The dates in the database are stored in yyyy-mm-dd format, so I need to first convert them to dd-mm-yyyy for better readability. When sub ...

Send a bundle of data through AJAX requests

An issue has been encountered on an HTML/PHP page named sucessful.php where a variable job_id passed from another page is not being received by the destination page interview.php. The problem arises when attempting to transfer two variables and their corr ...

Showing the JSON server response on the client side without using JQuery

I'm working on creating a function that can retrieve JSON server responses and then display the content from the JSON in a list on a webpage without relying on JQuery. Is there a way to accomplish this task? filterGet: function () { var ajax ...