-3

I'm trying to access a variable outside a function, but I'm getting undefined

 meliObject.get('users/me', function (err, res) {
           nickname = res.nickname;
  });

console.log(nickname);

How can I access nickname?

EDIT

I changed my code for:

var nickname;

        meliObject.get('users/me', function (err, res) {

            nickname = res.nickname;


        });

        console.log(nickname);

But I'm still getting undefined

Filipe Ferminiano
  • 8,373
  • 25
  • 104
  • 174

1 Answers1

1

The result of that function is asynchronous, so you cannot do this. Javascript flow goes like this: run meliObject.get, return immediately, run console.log(nickname), and then wait for the callback to be called. To console.log properly, just do this:

meliObject.get('users/me', function (err, res) {
   nickname = res.nickname;
   console.log(nickname);
});

Now, to answer your question, to declare a variable outside a function, just use var/let/const:

var a = 2;
(function () {
    a = 3;
})();
console.log(a);

It will print as expected.

Luan Nico
  • 5,376
  • 2
  • 30
  • 60
  • I changed my code in the question, but I'm getting undefined – Filipe Ferminiano Dec 10 '16 at 22:42
  • That's because of the first problem I described; your error was not scope, but actually asynchronousness. You need to put the console.log inside the callback function, because the order in which JS runs things (see my first paragraph for more details) – Luan Nico Dec 10 '16 at 23:04