Strange Behavior on Global and Local Variable in JavaScript

徘徊边缘 提交于 2019-12-11 03:09:52

问题


I tried following code:

var a = 5;

function x() {
  console.log(a);
}

x();

It runs as expected and prints 5.

But i changed the code so the global variable a will be overwrite as follows:

var a = 5;

function x() {
  console.log(a);
  var a = 1;
}

x();

It prints undefined. It doesn't make sense for me since the overwrite should be happened right after console.log(a). So what is the problem?


回答1:


This is happening because your second a variable is being 'hoisted' to the top of the function and it hides the first a. What is actually happening is this:

var a = 5;

function x() {
  var a;
  console.log(a);
  a = 1;
}

x();

Here is an article on hoisting from adequately good for further reading on the subject.




回答2:


var a = 5;

function x() {
    var a = 1;
console.log(a);
}

x();

you need to initalize variable a before console.log();



来源:https://stackoverflow.com/questions/15714752/strange-behavior-on-global-and-local-variable-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!