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:
Uncaught ReferenceError: test is not defined
This throws off a lot of developers, since this piece of code works fine:
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.
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);
Why Javascript code prints 'undefined' even when variable is declared global?
var regular = 'regular is assigned';
function prison() {
console.log(regular);
//var regular;
}
prison();
Cause is the commented out keyword.
Javascript move all the variables to the top before executing any code.
In your case, local variable regular
is printed instead first declared regular
variable.. Documentation
So Your code is executed as follows
var regular = 'regular is assigned';
function prison() {
var regular;//Moved here as per JS Scope
console.log(regular);//Hence it is undefined
}
prison();
javascript returns undefind for a globally declared variable
This is because after hoisting but before execution, your foo()
function internally looks like:
function foo() {
var a; // declaration hoisted to top
alert(a); // the local var is 'undefined' at this point
a = 890; // assignment operation not hoisted
alert(a);
}
Read more about hoisting here:
- http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
- http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
Javascript global object returning undefined in function
That code works fine. There must be something else that you're doing wrong in the rest of your code. Here's a snippet of it working:
var page = document.getElementById('example');
var p1_box = {
x: 20,
y: 20,
width: 560,
height: 400
};
function test(){
page.innerHTML = (p1_box.x);
}
test();
<div id="example"></div>
Related Topics
Jquery in Greasemonkey 1.0 Conflicts with Websites Using Jquery
Correct JavaScript Inheritance
How to Fix Client_Missing_Intents Error
Jqgrid Server Side Error Message/Validation Handling
Why Does ++[[]][+[]]+[+[]] Return the String "10"
Any Difference Between Await Promise.All() and Multiple Await
Es6 Class Variable Alternatives
How to Have a Default Option in Angular.Js Select Box
How to Add Hours to a Date Object
Last Segment of Url with JavaScript
Why Don't Logical Operators (&& and ||) Always Return a Boolean Result
Sort Array Elements (String with Numbers), Natural Sort
Does JavaScript Have "Short-Circuit" Evaluation
Is It Spread "Syntax" or the Spread "Operator"