Reputation: 151
I have a global (I think) variable which is declared on the the first line. In the function following it, I mean to use it but the computer tells me that the variable is undefined. Is this a scope problem and how do I fix it?
Here is my code:
var menustatus = 0;
function menuconfig() {
if (menustatus === 0) {
$('.menuhead2').animate({
top: "400px"
}, 300)
$('.menuhead3').animate({
top: "400px"
}, 300)
var menustatus = 1
}
}
Upvotes: 0
Views: 71
Reputation: 20524
At first I am providing the solution if anyone is interested to know what happened than please keep reading on.
Just remove the var keyword form the function scope menustatus. It will be solved then.
So instead of
var menustatus=1
Write
menustatus=1
This is happened because of javascript hoisting. Javascript floats any variable declaration (only) to the top of the scope. So your code actually looks like this :
var menustatus = 0;
function menuconfig() {
//It's floated on top of the scope
var menustatus;
if (menustatus === 0) {
$('.menuhead2').animate({
top: "400px"
}, 300)
$('.menuhead3').animate({
top: "400px"
}, 300)
menustatus = 1
}
}
So when executing this line :
if (menustatus === 0)
it find a scope variable menustatus which is not defined. And another thing to notice that it only hoist the declaration, not the assignment.
If we removes var
menustatus=1
then your code actually looks like this :
var menustatus = 0;
function menuconfig() {
//Nothing is hoisted here
//As no variable is declared here
if (menustatus === 0) {
$('.menuhead2').animate({
top: "400px"
}, 300)
$('.menuhead3').animate({
top: "400px"
}, 300)
menustatus = 1
}
}
As you do declare any variable, it is not floated on top.
Upvotes: 1
Reputation: 1006
Your function menuConfig() can access to the global scope where menustatus is first declared. The problem in your code is that you make an assignment in your menuConfig() function and then, the global menustatus is override by the menustatus variable in the function scope. Thus, JS logs undefined because your variable is assigned after it was declared.
Upvotes: 0
Reputation: 6170
You're declaring a local variable with the same name (menustatus
) inside your menuconfig
method:
var menustatus=0;
function menuconfig(){
if(menustatus===0){
$('.menuhead2').animate({
top:"400px"
},300)
$('.menuhead3').animate({
top:"400px"
},300)
// var menustatus=1
// replace with (notice no 'var')
menustatus=1;
}
}
The reason this happens is that JavaScript first looks for matching variables within the current scope.
In JavaScript, variables are function-scoped which means that it looks for variables named menustatus
within the current function. Since it finds one, it uses this variable first.
If a local function-scoped variable is not found, the JavaScript engine then looks at the parent scope. In this example, the parent scope is the "global" or window
scope.
Upvotes: 1