Why a variable defined global is undefined?
You have just stumbled on a js "feature" called hoisting
var myname = "global"; // global variable
function func() {
alert(myname); // "undefined"
var myname = "local";
alert(myname); // "local"
}
func();
In this code when you define func
the compiler looks at the function body. It sees that you are declaring a variable called myname
.Because of hoisting your code is rewritten to the following.Javascript Hoists variable and function declarations, by moving the declaration to the top of the function.
var myname = "global"; // global variable
function func() {
var myname; //declare local variable and assign it undefined
alert(myname); // "undefined"
myname = "local"; // assign local var myname to "local"
alert(myname); // "local"
}
func();
This "Covers" the global variable. If you want access to the global variable within the scope of a function use the this
keyword.var myname = "global"; // global variable
function func() {
var myname = "local";
alert(this.myname); // "global"
alert(myname); // "local"
}
func();
Note that this only works in calling a function not a method or constructor because the this
keyword changes what its bound to based on how you call a function.EDIT: For completeness
If you want to get access to global variables in any context regardless of function type then declare a global variable that by convention you never cover.
var global = this; // in global scope.
var myname = "global";
var obj = {f: function () {
var myname = "local";
console.log(global.myname);
}};
obj.f(); // "global"
Note that this is in method position and the this
keyword refers to obj directly and therefore doesn't have myname defined. Python Global Variables - Not Defined?
You have to use global df
inside the function that needs to modify the global variable. Otherwise (if writing to it), you are creating a local scoped variable of the same name inside the function and your changes won't be reflected in the global one.
p = "bla"
def func():
print("print from func:", p) # works, readonly access, prints global one
def func1():
try:
print("print from func:", p) # error, python does not know you mean the global one
p = 22 # because function overrides global with local name
except UnboundLocalError as unb:
print(unb)
def func2():
global p
p = "blubb" # modifies the global p
print(p)
func()
func1()
print(p)
func2()
print(p)
Output:bla # global
print from func: bla # readonly global
local variable 'p' referenced before assignment # same named local var confusion
bla # global
blubb # changed global
Why is variable undefined in global object even though it has not been defined?
What you're forbidden to do is reference a standalone identifier that the interpreter cannot resolve.
Referencing a property of an object - even if the property doesn't exist - is perfectly fine. It will result in undefined
, but it won't throw.
const obj = {};
console.log(obj.foo);
Surprised that global variable has undefined value in JavaScript
This phenomenon is known as: JavaScript Variable Hoisting.
At no point are you accessing the global variable in your function; you're only ever accessing the local value
variable.
Your code is equivalent to the following:
var value = 10;
function test() {
var value;
console.log(value);
value = 20;
console.log(value);
}
test();
Still surprised you're getting undefined
?Explanation:
This is something that every JavaScript programmer bumps into sooner or later. Simply put, whatever variables you declare are always hoisted to the top of your local closure. So, even though you declared your variable after the first console.log
call, it's still considered as if you had declared it before that.
However, only the declaration part is being hoisted; the assignment, on the other hand, is not.
So, when you first called console.log(value)
, you were referencing your locally declared variable, which has got nothing assigned to it yet; hence undefined
.
Here's another example:
var test = 'start';
function end() {
test = 'end';
var test = 'local';
}
end();
alert(test);
What do you think this will alert? No, don't just read on, think about it. What's the value of test
?If you said anything other than start
, you were wrong. The above code is equivalent to this:
var test = 'start';
function end() {
var test;
test = 'end';
test = 'local';
}
end();
alert(test);
so that the global variable is never affected.As you can see, no matter where you put your variable declaration, it is always hoisted to the top of your local closure.
Side note:
This also applies to functions.
Consider this piece of code:
test("Won't work!");
test = function(text) { alert(text); }
which will give you a reference error:This throws off a lot of developers, since this piece of code works fine:Uncaught ReferenceError: test is not defined
test("Works!");
function test(text) { alert(text); }
The reason for this, as stated, is because the assignment part is not hoisted. So in the first example, when test("Won't work!")
was run, the test
variable has already been declared, but has yet to have the function assigned to it.In the second example, we're not using variable assignment. Rather, we're using proper function declaration syntax, which does get the function completely hoisted.
Ben Cherry has written an excellent article on this, appropriately titled JavaScript Scoping and Hoisting.
Read it. It'll give you the whole picture in full detail.
Why this global variable is undefined inside a function?
It's because Javascript is not like Java and variable declaration are always pushed up their block. Your second piece of code is strictly equivalent to:
var a = 1;
function testscope(){
var a; // <-- When executed, the declaration goes up here
console.log(a, 'inside func');
a=2; // <-- and assignation stays there
};
testscope();
console.log(a, 'outside func');
Output
undefined "inside func"
1 "outside func"
Global Variable X is not defined error | Python Logic Error
The solution was actually to remove the Global declarations. As they weren't even required. I'll take some of the blame for being this stupid. Although I'll point the finger at the tutorial I was following.
Python error while using global variable. Name is not defined
The solution is simply to replace global res
with nonlocal res
.
The variable res
is not a global variable as it's defined within the scope of minOperations
. It is not a local variable (from ft_helper
's point-of-view) as it's not defined within ft_helper
's scope. Instead it is considered a nonlocal
variable from ft_helper
's point-of-view.
It you look at PEP 3104, you will see that nonlocal
was proposed precisely for situations like yours (accessing non-global variables from outer scopes).
Get only undefined value from my global variable configured with Context
You also need to define context provider and wrap your app into it.
export const RoundContextProvider = ({children}) => {
const stateTuple = useState(false);
return <RoundContext.Provider value={stateTuple}>{children}</RoundContext.Provider>;
}
<RoundContextProvider>
<YourApp/>
</RoundContextProvider>
then you can use it as you described in the question: const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext);
Global variable not working in NodeJS undefined
Here is a quick fix to your code. as being said before, since you do not return this value from the function you have to handle this logic inside the callback. Also, even if you would return a value, ko would still be uninitialized (when you tried to assign it's value to zo), since you use async action to get something from DB, and you do not wait for the data before you assign.
function getNumbers(callback) {
result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
if (err) throw err;
callback((result.length > 0) ? result[0].numbers : "");
});
}
var ko;
var zo;
getNumbers(function (result) {
ko = result;
console.log(result);
zo = ko;
});
here is an example for a code where zo will still be (given the function is not sync of course) undefined:function getNumbers(callback) {
result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", function (err, result) {
if (err) throw err;
callback((result.length > 0) ? result[0].numbers : "");
});
}
var ko;
getNumbers(function (result) {
ko = result;
console.log(result);
});
var zo = ko; //Not good!
Related Topics
What Do Double Brackets Mean in JavaScript and How to Access Them
Pass Parameter with Python Flask in External JavaScript
Remove Zero-Width Space Characters from a JavaScript String
JavaScript Es6 Typeerror: Class Constructor Client Cannot Be Invoked Without 'New'
Throttle Amount of Promises Open at a Given Time
Jsf/Primefaces Ajax Updates Breaks Jquery Event Listener Function Bindings
React 18, Useeffect Is Getting Called Two Times on Mount
Intercept Paste Event in JavaScript
Get Unique Results from JSON Array Using Jquery
How to Execute a Function on Pressing the Enter Key in an <Input> Field
How to Trigger Click on Page Load
Fix the Upstream Dependency Conflict Installing Npm Packages