Skip to content Skip to sidebar Skip to footer

Javascript Variable Is Undefined

First , let's see the code. var a=0; b=1; document.write(a); function run(){ document.write(b); var b=1; } run(); I think the result is 01 .but in fact , The result is 0un

Solution 1:

When you refer to a variable within a function JS first checks if that variable is declared in the current scope, i.e., within that function. If not found it looks in the containing scope. If still not found it looks in the next scope up, and so forth until finally it reaches the global scope. (Bear in mind that you can nest functions inside each other, so that's how you get several levels of containing scope though of course your exmaple doesn't do that.)

The statement:

b=1;

withoutvar declares a global variable that is accessible within any function, except that then in your first function you also declare a local b. This is called variable shadowing.

"But", you say, "I declare the local bafterdocument.write(b)". Here you are running into declaration "hoisting". A variable declared anywhere in a function is treated by the JS interpreter as if it had been declared at the top of the function (i.e., it is "hoisted" to the top), but, any value assignment happens in place. So your first function is actually executed as if it was like this:

functionrun(){
    var b;              // defaults to undefineddocument.write(b);  // write value of local b
    b=1;                // set value of local b
}

In your second function when you use this.b, you'll find that this refers to window, and global variables are essentially properties of window. So you are accessing the global b and ignoring the local one.

In your third function you don't declare a local b at all so it references the global one.

Solution 2:

When you write b = 1, you're creating a property in the global object. In an ordinary function, b will refer to this global.

Since your function contains var b;, b within the function refers to the local variable. (var statements create local variables throughout the function, no matter where the var is). However, the executable portion of the var statement (b = 1) is only executed at that point.

Solution 3:

The var directive is processed on the pre-execution stage, the b becomes local variable before document.write(b);, so at that time, b is undefined.

Note: assign a value to a variable is at the execution time, so you could image your code is like below.

functionrun(){
    document.write(b);
    var b=1;
}

is the same as:

functionrun(){
    var b;
    document.write(b);
    b=1;
}

Addtion:

This is why Put every var definition at the top of the function is good practice.

Solution 4:

This code work fine for me

if(var_name === "undefined"){
     alert(var_name+' : undefined');
   }

Post a Comment for "Javascript Variable Is Undefined"