show1
throws an error because variables declared with let
or const
cannot have any other variables with the same name initialized in that block (whether in an argument list or with const
/ let
/ var
).
Variables referenced by default parameters have odd scoping rules. Every argument essentially creates another block that that argument name can be defined in. So
const show3 = function(x, y = () => { x = 2; return x; }) {
is somewhat like (forgive the psuedo-code):
const show3 = < function >{
let x = firstArg;
{
let y = secondArg === undefined ? () => { x = 2; return x; } : secondArg;
{
// function body
When you simply assign to a variable name in the argument list, that argument will be overwritten. But when you use syntax to initialize a new variable (with var
), you've created another binding for that variable name, which is only visible inside the function body:
const show3 = {
let x = firstArg;
{
let y = secondArg === undefined ? () => { x = 2; return x; }
// the x referenced in the above line references the outer x, the first argument
{
// function body
// since "var x" is declared here, any references to "x" in this block
// will only reference the inner x
// but not the outer x
var x = /* something */
So, your show2
is reassigning the parameter named x
to 3 in the first line of the function body. In contrast, show3
is creating a new variable binding with the same name of x
, while the y
function's reference to x
is referencing the argument x
, which is different.
Why the results of show2 and show3 are different.
let's evaluate your code by this way
const show2 = function(x, y = () => {x.value = 2; return x;}) {
x = {name: "from argument", value: 3};
console.log(y());//{name: "from argument", value: 2}
console.log(x);//{name: "from argument", value: 2}
};
show2();
const show3 = function(x, y = () => {if(!x){x = {name:"from function", value: -1}}x.value = 2; return x;}) {
var x = {name: "from var", value: 3};
console.log(y());//{name: "from function", value: 2}
console.log(x);//{name: "from var", value: 3}
};
show3();
const show4 = function(x, y = () => {if(!x){x = {name:"from function", value: -1}}x.value = 2; return x;}) {
var x = {name: "from var", value: 3};
console.log(y());//{name: "from outside", value: 2}
console.log(x);//{name: "from var", value: 3}
};
show4({name:"from outside", value: -1})