nulled
nulled

Reputation: 423

JavaScript Variable Undefined, but it is not

So I have the following JavaScript which pulls user data from Facebook:

enter image description here

As you can see in that snippet I have included the line 'console.log(full_name);', which when ran successfully outputs the users full name into the browser console.

Then when I try this:

<script>document.write('Hello, ' + full_name);</script>

It doesn't work. It comes back with Uncaught ReferenceError: full_name is not defined.

I am confused as it is clearly defined & works when using console.log. Someone help?

Upvotes: 0

Views: 144

Answers (4)

binyoyo
binyoyo

Reputation: 11

<script>document.write('Hello, ' + full_name);</script>

you don't define the global variable full_name.

Upvotes: 1

Castyr
Castyr

Reputation: 380

It seems you are trying to render the name on the page. However, as @Andreas pointed out the document.write is executed as soon as that block is hit, which is before your Facebook API call is returned. Instead, try placing an id on the element you want the name to be rendered in and use getElementById within your callback. Something like this.

FB.api('/me', function(response) {
  document.getElementById('name').innerHTML = response.name;
});

Also, as others have mentioned, you are polluting your global scope with many variables by placing them within your call back without the var keyword.

Upvotes: 0

James Wright
James Wright

Reputation: 3010

In your example, invoking console.log(full_name) works because it's defined within that code. Referencing full_name in the inline script you specified won't work as it can't access the scope of the callback you pass to getLoginStatus; more specifically, in your example, it will look for full_name on the global object, which is window in the case of the browser. Thus, window.full_name is correctly undefined. In any case, there's also no guarantee that your callback will have been invoked by the time you invoke document.write.

To remedy this, you'll need to call document.write within your callback or store the value elsewhere for later retrieval. As an aside, you should avoid document.write.

Smashing Magazine has an article on JavaScript scope.

Upvotes: 0

loxxy
loxxy

Reputation: 13151

It definitely would throw an error.

Assuming that you are including the line

<script>document.write('Hello, ' + full_name);</script>

in the HTML directly, it will be executed much before the call getLoginStatus of fb API completes, which is where you have defined the global variable full_name

Not to mention this is a bad practice (Declaring global variables), but it is.

Upvotes: 0

Related Questions