JavaScript variable declaration details

  • 2020-03-30 04:25:50
  • OfStack

Those defined outside the function are global variables, while those defined inside the function are local variables. The definition here is declared through var.

JavaScript has an implicit global concept, meaning that any variable you don't declare becomes a global object property. Such as:


function test(){
    myname = "huming";
    alert(myname);
}
test();  // "huming"
alert(myname);  //"huming"

  The two results are the same, indicating that myname is a global variable.

So is there a difference between implicit global variables and explicitly defined global variables? The answer is definitely yes. Here's an example:


//Define three global variables
var global_test1 = 1;
global_test2 = 2; //Negative example
(function () {
    global_test3 = 3; //Negative example
}());
//Attempted to delete
delete global_test1; // false
delete global_test2; // true
delete global_test3; // true
//Test the delete
alert(typeof global_test1); // "number"
alert(typeof global_test2); // "undefined"
alert(typeof global_test3); // "undefined"

  As you can see from the above example, global_test1 defined by var outside of a function cannot be deleted, while both global_test2 and global_test3 not defined by var are deleted (whether created in the function body or not).

In summary, global variables declared via var outside of a function cannot be deleted, whereas implicit global variables can be deleted.

JavaScript to note here: there is a kind of behavior is called "hoisting" (mount/set-top parsing/analysis).

Here's an example:


var myname = "huming"; //Declare the global variable
function test() {
    alert(myname);
    var myname = "local_huming";
    alert(myname);
}
test();

  Do you think the two alerts are the same? Obviously not. Why not? The actual output is: "undefined", "local_huming".

The above example is equivalent to


var myname = "huming"; //Declare the global variable
function test() {
  var myname;
  alert(maname);<br>  myname = "local_huming";
  alert(myname);    // "local"
}
test();

The myname of the first alert output is not the global variable you thought it was, but a local variable in the same scope (a function body) as it is. Although it has not been declared, it is considered a declaration. This is known as "hoisting".

That should make sense. Errors can occur when you use a variable in the body of a function and then redeclare it later.

Writing specification:


function test() {
   var a = 1,
       b = 2,
       c = a + b,
       d = {},
       e,
       f;
   // function body...
}

 

The benefits are:

1. All local variables are defined at the beginning of the function for easy search;

2. Prevent logic errors that are used before variables are defined.

If you know javascript variable declaration, the above content is very detailed and easy to understand, the final summary is also very relevant, you should not miss it.


Related articles: