Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Printing Value of JS Variable in Console

Having some issues finding the value of a variable in the Chrome console.

I click one of the imageGallery elements, and it should store the value of the ahref attritube in my $capture variable.

But when I type console.log($capture); into the Chrome console it gives me an error: Uncaught ReferenceError: $capture is not defined

$('#imageGallery a').click(function(event){
    event.preventDefault();
    var $capture = $(this).attr('href');
});

2 Answers

Hi Chris,

You have declared $capture in the .click callback function, thus it is local to that. Either declare it out of the function or simply set it without the var, making it a global variable (or just execute the console.log in the function)

Everyone is beating me to these answers today! I can confirm that the "var" can be removed to create the desired outcome.

If you removed var it still wouldn't be defined outside the click function because it's using "this" - and it wouldn't know what "this" was outside the click function so you'd have to specify the selector rather than using "this" outside the function if that is what you wanted.

Snow Girl, it does work, I tried it in the console. After you click on the image, the href attribute value gets stored in the $capture variable, and you can then console.log($capture) and it prints out the value of the image you clicked on.

$('#imageGallery a').click(function(event){
    event.preventDefault();
    $capture = $(this).attr('href');
    console.log($capture);
});

If you click on the image, the function prints the $capture value to the console.

After that, you can type "console.log($capture)" into the console and the same value is returned.

k Alex, I see what you meant now - I was thinking without clicking anything - but yes, once the link is clicked it will store the variable as you said - good point, and this might be what Chris wants actually!

$capture is a variable that is defined within the scope of the click function. If you put the console.log inside the click function when you click the function you'll see the returned value of the variable. Outside the function this variable is not defined.