"undefined variable" error

This is because you’re using the variable (which exists only in the global scope) inside a function.