const show1 = function(x, y = () => {x = 2; return x;}) {
let x = 3;
console.log(y());
console.log(x);
};
show1();
const show2 = function(x, y = () => {x = 2; return x;}) {
x = 3;
console.log(y());
console.log(x);
};
show2();
const show3 = function(x, y = () => {x = 2; return x;}) {
var x = 3;
console.log(y());
console.log(x);
};
show3();
output
show1: Uncaught SyntaxError: Identifier 'x' has already been decalred;
show2: 2 2
show3: 2 3
Question
I was informed that there is a temporary dead zone where parameter variables are declared and initialized. See https://exploringjs.com/es6/ch_variables.html#sec_parameters-as-variables. So there are two scopes here, one is the parameter scope and the other is function scope.
- From the error in show1, I thought that there is a
x
variable already declared in this function. - According to Redeclaring a javascript variable. The re-declaration won't do anything to
x
(withvar
). Why the results ofshow2
andshow3
are different.
I posted the same question here If the variables are already declared at the beginning of function execution which was masked as duplicate. But I couldn't find anything useful for my doubt.