ReferenceError: variable is not defined

definition, javascript, var, variables

Solution

It's declared inside a closure, which means it can only be accessed there. If you want a variable accessible globally, you can remove the `var`:

$(function(){
    value = "10";
});
value; // "10"

This is equivalent to writing `window.value = "10";`.

Problem

I met this issue sometimes but still don't know what causes it. I have this script in the page: ``` $(function(){ var value = "10"; }); ``` But the browser says "ReferenceError: value is not defined". However if I go to the browser console and input either ``` 10 ``` or ``` var value = "10"; ``` either of them can return 10. What is the problem with my script?

Original source

Related problems