Strange behavior for global and local variables in JavaScript

I tried the following code:

var a = 5;

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

x();

Runs as expected and prints 5.

But I changed the code, so the global variable a will be overwritten as follows:

var a = 5;

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

x();

It prints undefined. This does not make sense to me, since rewriting should occur immediately after console.log (a). So what is the problem?

+2
source share
2 answers

This is because your second variable a"rises" at the top of the function, and it hides the first a. This actually happens:

var a = 5;

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

x();

Here is an article on getting up from good quality for further reading on the subject.

+5
source
var a = 5;

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

x();

a console.log();

0

Source: https://habr.com/ru/post/1589232/


All Articles