Q:

Jquery variable says TypeError: test is undefined

I have var test = $(this).attr('id');.  I have declared test as var but I do not understand
why I am getting 

TypeError: test is undefined. 

Why is this error appearing? 

A:

Your variable, test, is undefined because whatever this is (perhaps your window) doesn't have an id attribute.  As such, when you request the value of the non-existent attribute, undefined is returned, and assigned as the value of test.  It's very likely that you're confusing the contextual meaning of this. 
Below I'm calling this from the global scope, as well as in a callback function.  Notice the difference in their references.  Depending on where this is called, and how any surrounding functions are called, this can mean very different things. 
var outerTest = $(this).width(); // this is the window

$("img").on("click", function () {
    var innerTest = $(this).attr("id"); // this is the image
});

See: this on the Mozilla Developer Network

