[Solved] `$(“non_existing_element”);` returns `[ ]` in Console but `ReferenceError` when called as a variable in Console [closed]


30 90 seconds about variable scoping

$(document).ready(function(){
  var someVar = $("non_existing_element");
});

At this point, someVar does, in fact equal []. So if you were to write:

$(document).ready(function(){
  var someVar = $("non_existing_element");
  console.log("the value of someVar is", someVar);
});

You would see in your console

The value of someVar is []

Hooray!

But!

As soon as you pass that last curly bracket…

$(document).ready(function(){
  var someVar = $("non_existing_element");
}); // <<<<< This one

You have left the function defined by function() {}. Notice, it has no name, so this is called an anonymous function. Don’t worry, it does not have a vendetta against politics or the economy.

Once you leave the function, variables defined with var are no longer accessible. This is to prevent scope leak, which is a whole other conversation, which I’m sure you’ll be learning about very soon. Try defining it without var. See what happens.

Not using var will allow the variable to escape the clutch of the wretched anonymous function, and crap itself all over your global scope. (which, by the way is accessible through window.global_variable)

So, when you type a variable into your console (does not apply if you’re using breakpoints), variables are read from your global scope, since you are not inside any function. And since we just discovered that var scoped the variable to the function you’re not in, we now know why it is undefined.

I mean, imagine if there could only be one variable named checkbox! Every Javascript plugin you put in would conflict with each other. No one would know what checkbox was, and before you know it, crazy stuff is happening all over your DOM.

Moral of the story: Scope your variables. Understand your variables. Love your variables.

3

solved `$(“non_existing_element”);` returns `[ ]` in Console but `ReferenceError` when called as a variable in Console [closed]