Lack of defined global array in JavaScript

I'm encountering an issue with this JavaScript code. The second alert in the (tracking_data) is displaying 'undefined', as if the variable had been deleted or cleared, but I cannot find any part of the code that would cause that. Any assistance you could provide would be greatly appreciated. Regards.

var track_id = '';      // Name/ID of the exercise
var watch_id = null;    // ID of the geolocation
var tracking_data = []; // Array containing GPS position objects

$("#startTracking_start").on('click', function () {

// Start tracking the User
watch_id = navigator.geolocation.watchPosition(

    // Success
    function (position) {
        tracking_data.push(position);
        alert(tracking_data);
    },

    // Error
    function (error) {
        console.log(error);
    },

    // Settings
        {frequency: 3000, enableHighAccuracy: true });

    // Tidy up the UI
    track_id = $("#track_id").val();

    $("#track_id").hide();

    $("#startTracking_status").html("Tracking workout: <strong>" + track_id + "</strong>");
});


$("#startTracking_stop").on('click', function(){
    alert(tracking_data);

// Stop tracking the user
navigator.geolocation.clearWatch(watch_id);

// Save the tracking data
window.localStorage.setItem(track_id, JSON.stringify(tracking_data));

// Reset watch_id and tracking_data 
watch_id = null;
tracking_data = [];

// Tidy up the UI
$("#track_id").val("").show();

$("#startTracking_status").html("Stopped tracking workout: <strong>" + track_id + "</strong>");

});

Answer №1

Hoisting causes all var declarations to be moved to the top of their enclosing function. This means that you are actually overriding tracking_data within your function.

To solve this issue, simply change from var tracking_data = null; (inside your function) to just tracking_data = null;.

The following example demonstrates this behavior:

var v1 = 'hello';
(function(){
  console.log(v1); //prints hello
  v1 = 'hi';
  console.log(v1); //prints hi
})()

.

var v2 = 'hello';
(function(){
  console.log(v2); //prints undefined. Due to hoisting, the var v2 was overridden within this scope. 
  var v2 = 'hi';
  console.log(v2); //prints hi
})()

Answer №2

When you use let user_info = null, you are creating a local scope for the variable user_info within the click callback function. This is different from the user_info variable in the outer scope. Because of how JavaScript handles variable and function hoisting, declaring the variable at the start of the function makes it default to undefined.

To fix this issue, remove the let keyword on that line as well as the line before it. Your code should then function correctly.

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

Tips for maintaining the integrity of blank space within a text node?

When intercepting a paste event and cleaning HTML off of the content using textNodes, I am faced with an issue where all white space is reduced to a single space and new lines are disregarded. For example, pasting: "hello world !" ends up being "h ...

Exploring the synergies of Remark and Rehype plugins alongside MDX in Next.js powered by @next/mdx

I’ve been experimenting with Github Flavored Markdown using @next/mdx, but I’m struggling to understand how to use plugins alongside the code. Here’s a breakdown of what I’ve attempted so far: (I’m following the instructions from the Next.js Doc ...

Providing UI field attributes within server JSON data

Suppose I have numerous form fields that need to be displayed on the user interface. Additionally, in a standard Modify workflow, let's assume that these fields will have various attributes like value, mandatory, editable, disabled, label, regex (for ...

Generating nested arrays within an array continuously with numpy

I have two lists: a=[1,2,3] and b=[4,5,6] I decided to combine these lists into an array of arrays by using: c=np.array([[a],[b]]) Now I am wondering how to implement this in a loop. Can I create an empty array and then add arrays to it? If I call ...

Receiving a console notification about a source map error

Recently, I started receiving this warning in my console: "Source map error: request failed with status 404" resource URL: map resource URL: shvl.es.js.map" Has anyone encountered this issue before? I'm unsure of what it might be? This is my webpa ...

Maintain original image file name when downloading

I have successfully created a download link containing a base 64 encoded image. The only issue is that I need to retain the original file name, which is dynamic and cannot be hardcoded. downloadImage: function(){ var image_url = document.getEleme ...

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

What is the best way to select multiple items using mongoose?

For instance, consider this list: [ { name: "John" }, { name: "Mike" }, { name: "Homer" }, { name: "Bart" }, { name: "Dmitry" }, { name: "Dan" } ] If I want to select specific objects ...

Can someone guide me on the proper implementation of the 'useEffect' hook in React version 18?

I'm currently working on a project following a YouTube tutorial that uses React 17, while I'm using React 18. Everything has been going smoothly so far, but I've hit a roadblock with formatting animated text. The specific task I'm stuck ...

Browsing through a collection of JSON objects with a user interface

I need a way to filter and display a list of Dogs based on a search query. I initially stored the data in an array within the state, but with an increasing number of entries, I've decided to switch to JSON format for better management. However, I&apo ...

Extracting HTML elements between tags in Node.js is a common task faced

Imagine a scenario where I have a website with the following structured HTML source code: <html> <head> .... <table id="xxx"> <tr> .. </table> I have managed to remove all the HTML tags using a library. Can you suggest w ...

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

Is there a way to include this function in an array without triggering it right away?

In my coding project, I am working with an array of functions that return jQuery deferred AJAX objects known as phoneAjaxCalls. The main function called newPhone is where multiple calls are being pushed and it requires two arguments. function newPhone(tlc ...

How to capture the "chip close" event in Vuetify

Exploring the vuetify realm as a newcomer, I find myself grappling with event handling while working on my first web app project. Specifically, I am currently developing a "UserPicker" component using VAutocomplete. This component functions by sending an ...

The issue with Three.js responsive canvas is that it fails to properly adjust the size of the

I'm currently working on a threejs basic scene and attempting to create a responsive canvas for a full-screen experience. However, the mesh inside the scene is not resizing correctly as expected. Instead of remaining a cube, it distorts into a rectang ...

Troubleshooting an issue with an AJAX request

Having trouble getting the HTML back from an AJAX call - works in FF but returns "null" in IE when using alert(result.html()); Here's the code, any suggestions? Thanks! The errors variable is also null in IE. It doesn't matter what element I u ...

What is the process for updating the Vue template during runtime?

Currently, I am working on a CMS-based Vue page. Within this page, there is a root container that contains two child containers structured as follows: <div id="app"> <div class="above-the-fold">...</div> <di ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Ensure that the React Material UI Textfield with the type "number" is validated to have exactly 10 characters

<TextField variant="outlined" required fullWidth id="accno" label="Main Account Number" type="number" name="accno" //inputProps={{ className:"input-acc", pattern: "^.{0,10}$"}} autoComplete="accno" onChange={(e) = ...