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

Navigating the file paths for Vue.js assets while utilizing the v-for directive

Recently, I started working with Vue.js and found it simple enough to access the assets folder for static images like my logo: <img src="../assets/logo.png"> However, when using v-for to populate a list with sample data, the image paths se ...

Angular Circumstance

Can you help me out? I am trying to figure out how to create an IF...ELSE condition using AngularJS on my index.html file: <ons-list-item modifier="chevron" class="list-item-container" ng-repeat="item in categories track by $index"> <a href="#/pa ...

Cannot get Firebase's set() method to work when called within onAuthStateChanged() function

As I embark on developing my first significant web application using ReactJS with Firebase as the backend database, everything was progressing smoothly until a troublesome issue surfaced. The hurdle I encountered involves saving user information upon thei ...

Efficiently search and filter items across multiple tabs using a single search bar in the Ionic 2

I am currently working on implementing a single search bar that can filter lists in 2 different tabs within Ionic 2. The search bar is functional, and I have a method for filtering through objects. However, my goal is to allow users to select different tab ...

ESLint only lints certain errors in the command-line interface

Incorporating eslint into my project has been a game-changer. Here's how my .eslintrc file is set up: // http://eslint.org/docs/rules { "parser": "babel-eslint", "env": { "browser": true, "node": true, "mocha": true }, "plugins": ...

Issue with Vue JS component on blade template page

Having trouble loading a Vue component into a Laravel blade file? Despite making changes, the content of my vue file isn't showing up in the blade file - even though there are no errors in the console. Any suggestions on how to resolve this issue woul ...

Utilizing Vue's v-for directive to display computed properties once they have been fully loaded

Utilizing the v-for directive to loop through a computed property, which is dependent on a data attribute initialized as null. I'm planning to load it during the beforeMount lifecycle hook. Here's a simplified version of the code: <th v-for= ...

Is there a way to convert this JSON object into HTML table code?

I've been working on tweaking a code snippet I came across, but I'm struggling to get it to function the way I desire. Here is the current Javascript code: function JsonUtil() { /** * Given an object, * return its type as a string. ...

Is it feasible to cancel or clear the queue for a jQuery fadeOut function after a delay is specified? If so,

Can anyone help me out with this question? Is there a way to eliminate the delay in chaining? Mn.Base.TopBox.show = function(timedur){ $('#element').fadeIn().delay(timedur).fadeOut(); } Mn.Base.TopBox.cancelFadeout = function(){ } I&apos ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

Generating progress bar in Javascript while exporting CSV fileCan JavaScript export CSV and

Looking for a way to add a progress bar while generating and serving a CSV file via ajax? The database-heavy process is causing a delay, so I need a loader on the screen that disappears once the task is complete. It should be done with ajax or stay on th ...

``There is an issue with the onsubmit property that prevents the opening of

I have encountered an issue with my forms that has me stumped. Despite searching online for help, I can't seem to figure out why my implementation is not working as intended. The concept is straightforward. I've embedded a form within a JSP page ...

Unspecified tag name attribute in Vue that can be accessed in the browser

At the moment, I have encountered an issue with a selector in Vue returning undefined for {{ lens.price }}. However, when I use a = lens[1].getAttribute('price') in the browser console, it correctly displays the value as "0". Why is Vue showing ...

JavaScript JSON YouTube API viewCount function is not functioning correctly

I'm struggling to retrieve the views of a video using JavaScript (Chrome Extension). Here is the code I have so far: $(function() { $.getJSON('http://gdata.youtube.com/feeds/api/videos/H542nLTTbu0?alt=json',function(data) { ...

JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code. When the stylesheets are directly embedded ...

Tips for concealing tick labels in d3 using TypeScript

When trying to hide tick labels by passing an empty string to the .tickFormat("") method, I encountered an issue with Typescript. The error message received was as follows: TS2769: No overload matches this call. Overload 1 of 3, '(format: null): Axi ...

Choose a minimum of one validation for the list item

When I have a form in JSP that includes a drop-down view with multiple options, I want to ensure that at least one option is selected before the form can be submitted. If no options are selected, the form should not be able to submit. Thank you in advance ...

data not populating in datagrid upon first load

I'm facing an issue where the data I'm trying to fetch using an API is not initially loading in my datagrid. I can retrieve the data successfully, but for some reason, it doesn't show up in the datagrid. The setup involves a common function ...

Endless loop caused by Angular UI-router's promise resolving

I'm attempting to retrieve data from my SQLite database before loading a view using resolve when defining the state in ui-router. Currently, this is how I've set up the state: .state("menu", { templateUrl: "templates/menu.html", control ...

Changes to the parent state will not be reflected in the child props

When the child component PlaylistSpotify updates the state localPlaylist of its parent, I encounter an issue where the props in PlaylistSpotify do not update with the new results. I've been struggling to figure out what I'm missing or doing wrong ...