0

It seems like I can't access variable outside a function if globally defined.

var test;

function foo() { 
$.ajax({
    url: '[MY LINK]',
        dataType: 'json',
        type: 'get',
        cache: false,
        success: function(data) {
            $(data.feeds).each(function(index, value) {
                var value = parseFloat(value.field1);
                test = 10;
           });
        }
    });
 }

console.log(test)

What I see in my console is:

undefined

I've tried not to declare the variable into global scope but that way it returns an error:

Uncaught ReferenceError: test is not defined at index.js:80

According to what I read on the web not writing "var" for a variable makes it globally available.

antonioag
  • 389
  • 1
  • 3
  • 15
  • 3
    ajax is asynchronous function. your console.log is executed before test is set to 10. PS: as other mentioned, I guess that console.log is in top scope – bigless Jan 28 '18 at 19:40
  • 2
    Is that the complete code? It is missing the closing }) for the $.ajax call. Where do those go? We need to see in which context the console.log(test) is called – joshua miller Jan 28 '18 at 19:41
  • Please don't just drop relevant parts of the code, we can't assume based on the indentation where `console.log(test)` is located – Alon Eitan Jan 28 '18 at 19:42
  • I just wrote an answer with snippet and long educational explanation, why this happens ... :) – Rauli Rajande Jan 28 '18 at 19:51
  • I edited the code, "async:false" works but I know it is not recommended. console.log is at the end – antonioag Jan 28 '18 at 20:00
  • The first comment is correct. When an async process begins, the next line of code is processed before the async process completes. – Jeff Matthews Jan 28 '18 at 20:05

0 Answers0