The output is:
javascript
var a = 0;
if(true){
var a = 1;
console.log(a); //1
}
console.log(a); //1
C
int a = 0;
if(1){
int a = 1;
printf("%i ", a); //1
}
printf("%i ", a); //0
Python
a = 0
if True:
a = 1
print a #1
print a #1
That because javascript and Python doesn't have block scope; so anything declared in an if
block has the same scope as anything declared exactly outside the block (and Python doesn't use declaration).
C have block scope. If you declare a static variable inside a block {...}
, the variable is no more accessible outside the block.
The same is for all the block types like for
, else
, elseif
...
In javascript if you want to declare a variable exclusive inside a block you can use let
:
Variables declared by let have as their scope the block in which they
are defined, as well as in any contained sub-blocks . In this way, let
works very much like var. The main difference is that the scope of a
var variable is the entire enclosing function
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
and here a lot of examples about javascript scope: https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/