JavaScript Global Variables Explained

I have encountered an issue where I want to access the single_video variable outside of the controller function in my AngularJS application. It seems to be working fine and printing correctly in the first console.log statement. However, when attempting to access it in the second console.log statement outside of the controller function, I am getting an error saying that single_video is undefined. As someone who is still learning JavaScript and AngularJS, this has been quite confusing for me.

   var single_video;
    var app = angular.module('myApp', []);
    app.controller('randomVideo', function($scope, $http) {
        var onSuccess = function(response){
            $scope.video = response.data; 
            single_video = $scope.video;
            //First console.log
            console.log('1st ID='+single_video.yt_id);
        };
        var onError = function(reason){
            $scope.error = "There is an error about getting random_video.php";
        };
       $http.get("http://www.ytmdb.com/ytvideo/api/random_video.php")
       .then(onSuccess, onError);
    });
    //Second console.log
    console.log('2nd ID='+single_video.yt_id);

Answer №1

When the single_video variable is declared, it does not have a defined value at the time of calling the second console.log().

Actually, the first console.log is executed after the second one because you only defined some functions without executing them and setting values before calling the "second console.log".

Answer №2

Your variable is perfectly fine. It seems like your second console.log gets triggered before the first one.

I recommend looking up "javascript async" or "javascript callback" to grasp how asynchronous code functions.

In short, when you use "$http.get," it sends an HTTP request to a server that will reply after some time. Your variable is only set once the server responds and triggers the "onSuccess" callback.

However, your second console.log runs right after the HTTP request is initiated - meaning before the server's response and the "onSuccess" callback.

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

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Tips for implementing Animation.css in Angular version 1.5.8

I have successfully added the ngAnimate dependency to my AngularJS project: var app=angular.module('testApp',['ngRoute', 'ngAnimate']); I have also included the animation classes in my animation.css file: .slide-animation.n ...

When the page loads, should the information be transmitted in JSON format or should PHP be responsible for formatting it?

I'm considering whether it would be more server-efficient and effective to send data to the user in JSON format upon page load, with JavaScript handling the conversion into readable information. For instance, when a user visits my index page, instead ...

JavaScript | Determining the coordinates of where on the image X and Y were clicked

My goal is to determine the position of an x and y location when a user clicks on an image. This information will be used to add a spot to the image that displays relevant information. The content for the spot will be dynamically loaded from a SQL database ...

Develop an engaging billboard carousel using jQuery

After coming across a tutorial on tympanus, I decided to make some modifications to create a rotating billboard effect. However, something seems to be going wrong and it's driving me crazy trying to figure out the problem! $(function() { $('#ad_ ...

Steps for eliminating an element using jQuery from a variable filled with HTML code

I'm developing a forum where users have the ability to quote other users' comments. When a user clicks on "quote" for a comment, it captures the HTML of that comment and displays it in a box that says Quote: Original post by a member, similar t ...

What could be the reason for my jQuery focusout (or blur) event failing to trigger?

On the jsfiddle link provided, the HTML code at the end section looks like this: <input type="text" id="BLAboxPaymentAmount" value="2"> </br> <input type="text" id="BLAboxSection5Total" value="3"> Below that is the jQuery code snippet: ...

The error message "Exceeded the maximum call stack size in Javascript"

My current project involves using socket.io for sending and receiving data from a server. I have implemented a "Create Game" button on the client side that triggers the creation of a new GameServer on the server side. Following that, I am displaying the ga ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...

What is the best way to determine if certain rows of data have been successfully loaded when working with Ext.data.operation and an ajaxProxy?

Here is the provided code snippet: Ext.define('Book', { extend: 'Ext.data.Model', fields: [ {name: 'id', type: 'int'}, {name: 'title', type: 'string'}, {name: &apo ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

The rule "react/jsx-sort-props" does not have a valid configuration

I've been attempting to organize props names alphabetically using the eslint-plugin-react plugin but I keep encountering this error: [Error ] .eslintrc.json: Configuration for rule "react/jsx-sort-props" is invalid: Value {"callbacksLast":true,"shorth ...

Establish attributes within a complex mongoose schema model

Below is the structure of my schema: var userschema = new mongoose.Schema({ user: String, imagen: [{ title: String, name: String, path: String, }] }); Currently, I am attempting the following: ...

An effective method for extracting values from a JSON array and populating them in a Selection (drop down)

Currently in the process of learning jquery, I have started working on an application within phonegap... I am looking to populate a dropdown list with a series of values... "data": [ { "city_id": "1", "city": "test1" }, { "c ...

What is the best way to create a function that can disable console.log and be imported into other React files for easy access?

Here is the content of my static.js file: var Helper = { console.log: function(){ }, Login: function(){ var name; var password; //rest of the code } } module.exports = Helper; Now, in my test.js file: var Helper ...

What is the correct way to utilize async/await in a React render function?

Although I am quite familiar with using async await in back end development with nodejs, I recently encountered a scenario where I needed to apply it on the front end. The task involves receiving an array of objects containing the latitude and longitude ( ...

Can Vuejs delay the calculation of a computed property until the component is "ready"?

Within my Vue.js application, I have a `computed` property that relies on a value fetched from an AJAX call. I am looking for a way to delay the calculation of this `computed` property until after the `ready` method has completed. While everything is fun ...

Monitoring the sharing of content on social media networks, rather than tracking individual

After setting up a hidden page on my site and configuring buttons to test pushing data to the dataLayer, I have ensured that my Google Tag Manager (gtm) is functioning properly. I recently tracked a Google +1 button click successfully, confirming that my c ...

CSS linking causing pages to crumble

Out of nowhere, while working on my project today, my page suddenly collapsed. It was a frustrating sight to see. Immediately, I went back to Dreamweaver and used cmd+z to undo a few steps, but there was no visible issue. Despite this, my page continued t ...

What could be causing the discrepancy between the labels below the chart and the labels in the legend on the bar chart in Chart.js?

I'm looking to create a chart with labels on the xAxes and the same labels in the legend. I've tried various solutions, but so far, the best result I've achieved is shown in the code snippet below. However, all bars seem to be connected to m ...