declaring a variable twice in IIFEScope of Default function parameters in javascriptWhy would a JavaScript variable start with a dollar sign?How do you use a variable in a regular expression?What is the scope of variables in JavaScript?How do you check if a variable is an array in JavaScript?How do I declare a namespace in JavaScript?How to determine if variable is 'undefined' or 'null'?Check if a variable is a string in JavaScriptRead environment variables in Node.jsJavaScript check if variable exists (is defined/initialized)Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Banach space and Hilbert space topology

What Brexit solution does the DUP want?

Is Social Media Science Fiction?

How do I create uniquely male characters?

Why has Russell's definition of numbers using equivalence classes been finally abandoned? ( If it has actually been abandoned).

The magic money tree problem

What makes Graph invariants so useful/important?

Shell script can be run only with sh command

The use of multiple foreign keys on same column in SQL Server

Prevent a directory in /tmp from being deleted

What are these boxed doors outside store fronts in New York?

Extreme, but not acceptable situation and I can't start the work tomorrow morning

A newer friend of my brother's gave him a load of baseball cards that are supposedly extremely valuable. Is this a scam?

What is the command to reset a PC without deleting any files

Accidentally leaked the solution to an assignment, what to do now? (I'm the prof)

Simulate Bitwise Cyclic Tag

Why is the design of haulage companies so “special”?

How to calculate implied correlation via observed market price (Margrabe option)

"which" command doesn't work / path of Safari?

Why is "Reports" in sentence down without "The"

Are white and non-white police officers equally likely to kill black suspects?

Can I interfere when another PC is about to be attacked?

If Manufacturer spice model and Datasheet give different values which should I use?

I see my dog run



declaring a variable twice in IIFE


Scope of Default function parameters in javascriptWhy would a JavaScript variable start with a dollar sign?How do you use a variable in a regular expression?What is the scope of variables in JavaScript?How do you check if a variable is an array in JavaScript?How do I declare a namespace in JavaScript?How to determine if variable is 'undefined' or 'null'?Check if a variable is a string in JavaScriptRead environment variables in Node.jsJavaScript check if variable exists (is defined/initialized)Is there a standard function to check for null, undefined, or blank variables in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








15















I came through this fun quiz on the internet.



console.log((function(x, f = (() => x))
var x;
var y = x;
x = 2;
return [x, y, f()]
)(1))


and the choices were:



  1. [2,1,1]


  2. [2, undefined, 1]


  3. [2, 1, 2]


  4. [2, undefined, 2]


I picked solution 2 TBH, basing that on that x has been redefined, y was declared and defined with no value, and that f has a different scope hence getting the global x memory spot than function x memory spot.



However, I tried it in jsbin.com



and I found it was solution 1, while I was not sure why that happened I messed with the function body and I removed var x from the function body, I found that the response changed to #3 which makes sense as x value changed and hence it showed x and f as 2 and y as 1 which was declared globally.



but still I can't get why it shows 1 instead of undefined.










share|improve this question

















  • 1





    I find the best way to figure these things out is to step through them line by line with a debugger, and/or print out the values after each line.

    – Heretic Monkey
    13 hours ago











  • var x; doesn't define a new variable within the function scope, where var x = somevalue; would

    – Alex
    13 hours ago






  • 2





    @alex it does. ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms I see, would have expected x to be undefined then, implicitly copy the function formal value looks really odd to me.

    – Alex
    12 hours ago






  • 3





    I'm glad this question was asked :)

    – Pointy
    12 hours ago

















15















I came through this fun quiz on the internet.



console.log((function(x, f = (() => x))
var x;
var y = x;
x = 2;
return [x, y, f()]
)(1))


and the choices were:



  1. [2,1,1]


  2. [2, undefined, 1]


  3. [2, 1, 2]


  4. [2, undefined, 2]


I picked solution 2 TBH, basing that on that x has been redefined, y was declared and defined with no value, and that f has a different scope hence getting the global x memory spot than function x memory spot.



However, I tried it in jsbin.com



and I found it was solution 1, while I was not sure why that happened I messed with the function body and I removed var x from the function body, I found that the response changed to #3 which makes sense as x value changed and hence it showed x and f as 2 and y as 1 which was declared globally.



but still I can't get why it shows 1 instead of undefined.










share|improve this question

















  • 1





    I find the best way to figure these things out is to step through them line by line with a debugger, and/or print out the values after each line.

    – Heretic Monkey
    13 hours ago











  • var x; doesn't define a new variable within the function scope, where var x = somevalue; would

    – Alex
    13 hours ago






  • 2





    @alex it does. ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms I see, would have expected x to be undefined then, implicitly copy the function formal value looks really odd to me.

    – Alex
    12 hours ago






  • 3





    I'm glad this question was asked :)

    – Pointy
    12 hours ago













15












15








15


5






I came through this fun quiz on the internet.



console.log((function(x, f = (() => x))
var x;
var y = x;
x = 2;
return [x, y, f()]
)(1))


and the choices were:



  1. [2,1,1]


  2. [2, undefined, 1]


  3. [2, 1, 2]


  4. [2, undefined, 2]


I picked solution 2 TBH, basing that on that x has been redefined, y was declared and defined with no value, and that f has a different scope hence getting the global x memory spot than function x memory spot.



However, I tried it in jsbin.com



and I found it was solution 1, while I was not sure why that happened I messed with the function body and I removed var x from the function body, I found that the response changed to #3 which makes sense as x value changed and hence it showed x and f as 2 and y as 1 which was declared globally.



but still I can't get why it shows 1 instead of undefined.










share|improve this question














I came through this fun quiz on the internet.



console.log((function(x, f = (() => x))
var x;
var y = x;
x = 2;
return [x, y, f()]
)(1))


and the choices were:



  1. [2,1,1]


  2. [2, undefined, 1]


  3. [2, 1, 2]


  4. [2, undefined, 2]


I picked solution 2 TBH, basing that on that x has been redefined, y was declared and defined with no value, and that f has a different scope hence getting the global x memory spot than function x memory spot.



However, I tried it in jsbin.com



and I found it was solution 1, while I was not sure why that happened I messed with the function body and I removed var x from the function body, I found that the response changed to #3 which makes sense as x value changed and hence it showed x and f as 2 and y as 1 which was declared globally.



but still I can't get why it shows 1 instead of undefined.







javascript iife






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 13 hours ago









Hamza MohamedHamza Mohamed

689423




689423







  • 1





    I find the best way to figure these things out is to step through them line by line with a debugger, and/or print out the values after each line.

    – Heretic Monkey
    13 hours ago











  • var x; doesn't define a new variable within the function scope, where var x = somevalue; would

    – Alex
    13 hours ago






  • 2





    @alex it does. ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms I see, would have expected x to be undefined then, implicitly copy the function formal value looks really odd to me.

    – Alex
    12 hours ago






  • 3





    I'm glad this question was asked :)

    – Pointy
    12 hours ago












  • 1





    I find the best way to figure these things out is to step through them line by line with a debugger, and/or print out the values after each line.

    – Heretic Monkey
    13 hours ago











  • var x; doesn't define a new variable within the function scope, where var x = somevalue; would

    – Alex
    13 hours ago






  • 2





    @alex it does. ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms I see, would have expected x to be undefined then, implicitly copy the function formal value looks really odd to me.

    – Alex
    12 hours ago






  • 3





    I'm glad this question was asked :)

    – Pointy
    12 hours ago







1




1





I find the best way to figure these things out is to step through them line by line with a debugger, and/or print out the values after each line.

– Heretic Monkey
13 hours ago





I find the best way to figure these things out is to step through them line by line with a debugger, and/or print out the values after each line.

– Heretic Monkey
13 hours ago













var x; doesn't define a new variable within the function scope, where var x = somevalue; would

– Alex
13 hours ago





var x; doesn't define a new variable within the function scope, where var x = somevalue; would

– Alex
13 hours ago




2




2





@alex it does. ...

– Jonas Wilms
13 hours ago





@alex it does. ...

– Jonas Wilms
13 hours ago













@JonasWilms I see, would have expected x to be undefined then, implicitly copy the function formal value looks really odd to me.

– Alex
12 hours ago





@JonasWilms I see, would have expected x to be undefined then, implicitly copy the function formal value looks really odd to me.

– Alex
12 hours ago




3




3





I'm glad this question was asked :)

– Pointy
12 hours ago





I'm glad this question was asked :)

– Pointy
12 hours ago












2 Answers
2






active

oldest

votes


















17















but still I can't get why it shows 1 instead of undefined.




It's not just you. This is a deep, dark part of the specification. :-)



The key here is that there are two xs. Yes, really. There's the parameter x, and there's the variable x.



A parameter list containing expressions (like f's default value) has its own scope separate from the function body's scope. But prior to parameter lists possibly having expressions, having var x within a function with an x parameter had no effect (x was still the parameter, with the parameter's value). So to preserve that, when there's a parameter list with expressions in it, a separate variable is created and the value of the parameter is copied to the variable at the beginning of the function body. Which is the reason for this seemingly-odd (no, not just seemingly) odd behavior. (If you're the kind who likes to dive into the spec, this copying is Step 28 of FunctionDeclarationInstantiation.)



Since f's default value, () => x, is created within the parameter list scope, it refers to the parameter x, not the var.



So the first solution, [2, 1, 1] is correct, because:




  • 2 was assigned to the var x in the function body. So at the end of the function, the var x is 2.


  • 1 was assigned to y from the var x before x got the value 2, so at the end of the function, y is 1.

  • The parameter x's value has never changed, so f() results in 1 at the end of the function

It's as though the code were written like this instead (I've removed unnecessary parens and added missing semicolons):






console.log(function(param_x, f = () => param_x) 
var var_x = param_x;
var y = var_x;
var_x = 2;
return [var_x, y, f()];
(1));






...I removed var x from the function body, I found that the response changed to #3...




#3 is [2, 1, 2]. That's correct, because when you remove the var x from the function, there's only one x, the parameter (inherited by the function body from the parmeter list). So assigning 2 to x changes the parameter's value, which f returns.



Taking the earier example with param_x and var_x, here's what it looks like if you remove the var x; from it:






console.log(function(param_x, f = () => param_x) 
var y = param_x;
param_x = 2;
return [param_x, y, f()];
(1));






Here's an annotated description of the original code (with the extraneous parentheses removed and missing semicolons added):



// /---- the parameter "x"
// v vvvvvvvvvvv--- the parameter "f" with a default value
console.log(function(x, f = () => x)
var x; // <=== the *variable* x, which gets its initial value from the
// parameter x
var y = x; // <=== sets y to 1 (x's current value)
x = 2; // <=== changes the *variable* x's value to 2
// +---------- 2, because this is the *variable* x
// (1));



Final note regarding your title:




declaring a variable twice in IIFE




The variable is only declared once. The other thing is a parameter, not a variable. The distinction is rarely important...this being one of those rare times. :-)






share|improve this answer




















  • 1





    This is now in my list of "new weird things about JavaScript" alongside the semantics of (not yet really standard) instance property initialization expressions in class declarations.

    – Pointy
    12 hours ago











  • @Pointy - Oh, this is much weirder than field declarations. :-D

    – T.J. Crowder
    12 hours ago











  • Well field declarations are jarring to me because this is the instance, not the this of the surrounding scope as with object initializers. I guess it's not really "weird" if you think of class declarations as being something akin to macro expansion.

    – Pointy
    12 hours ago











  • @Pointy - Yeah. I think of them as code that's relocated to the beginning of the constructor (just after the super call if it's a subclass). That's what Java does with instance field initializers and instance initialization blocks (and they're literally copied to the beginning of each constructor in Java; thankfully in JavaScript we just have the one). JavaScript took effectively the same approach.

    – T.J. Crowder
    12 hours ago



















1














The tricky part of that code is that the => function is created as part of a default parameter value expression. In parameter default value expressions, the scope includes the parameters declared to the left, which in this case includes the parameter x. Thus for that reason the x in the => function is in fact the first parameter.



The function is called with just one parameter, 1, so when the => function is called that's what it returns, giving [2, 1, 1].



The var x declaration, as Mr Crowder points out, has the (somewhat weird, at least to me) effect of making a new x in the function scope, into which is copied the value of the parameter x. Without it, there's only the one (the parameter).






share|improve this answer

























  • That still does not explain why removing var x; results in 2, 1, 2 ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms you're right; the var declaration must ... do something but it doesn't seem obvious to me what that is. It's as if the var declaration creates a new x in the function scope, but it clearly gets the value of the parameter x anyway (which I'd expect), leaving the parameter apparently in its own scope.

    – Pointy
    13 hours ago











  • I guess the values are somewhat copied from the default initializers scope to the bodies scope. Im already digging into the spec

    – Jonas Wilms
    13 hours ago











  • It makes sense. As noted in the spec: NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body. thats reasonable.

    – Jonas Wilms
    12 hours ago











  • @Pointy - It's a very deep, dark part of the spec. :-)

    – T.J. Crowder
    12 hours ago











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55560027%2fdeclaring-a-variable-twice-in-iife%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









17















but still I can't get why it shows 1 instead of undefined.




It's not just you. This is a deep, dark part of the specification. :-)



The key here is that there are two xs. Yes, really. There's the parameter x, and there's the variable x.



A parameter list containing expressions (like f's default value) has its own scope separate from the function body's scope. But prior to parameter lists possibly having expressions, having var x within a function with an x parameter had no effect (x was still the parameter, with the parameter's value). So to preserve that, when there's a parameter list with expressions in it, a separate variable is created and the value of the parameter is copied to the variable at the beginning of the function body. Which is the reason for this seemingly-odd (no, not just seemingly) odd behavior. (If you're the kind who likes to dive into the spec, this copying is Step 28 of FunctionDeclarationInstantiation.)



Since f's default value, () => x, is created within the parameter list scope, it refers to the parameter x, not the var.



So the first solution, [2, 1, 1] is correct, because:




  • 2 was assigned to the var x in the function body. So at the end of the function, the var x is 2.


  • 1 was assigned to y from the var x before x got the value 2, so at the end of the function, y is 1.

  • The parameter x's value has never changed, so f() results in 1 at the end of the function

It's as though the code were written like this instead (I've removed unnecessary parens and added missing semicolons):






console.log(function(param_x, f = () => param_x) 
var var_x = param_x;
var y = var_x;
var_x = 2;
return [var_x, y, f()];
(1));






...I removed var x from the function body, I found that the response changed to #3...




#3 is [2, 1, 2]. That's correct, because when you remove the var x from the function, there's only one x, the parameter (inherited by the function body from the parmeter list). So assigning 2 to x changes the parameter's value, which f returns.



Taking the earier example with param_x and var_x, here's what it looks like if you remove the var x; from it:






console.log(function(param_x, f = () => param_x) 
var y = param_x;
param_x = 2;
return [param_x, y, f()];
(1));






Here's an annotated description of the original code (with the extraneous parentheses removed and missing semicolons added):



// /---- the parameter "x"
// v vvvvvvvvvvv--- the parameter "f" with a default value
console.log(function(x, f = () => x)
var x; // <=== the *variable* x, which gets its initial value from the
// parameter x
var y = x; // <=== sets y to 1 (x's current value)
x = 2; // <=== changes the *variable* x's value to 2
// +---------- 2, because this is the *variable* x
// (1));



Final note regarding your title:




declaring a variable twice in IIFE




The variable is only declared once. The other thing is a parameter, not a variable. The distinction is rarely important...this being one of those rare times. :-)






share|improve this answer




















  • 1





    This is now in my list of "new weird things about JavaScript" alongside the semantics of (not yet really standard) instance property initialization expressions in class declarations.

    – Pointy
    12 hours ago











  • @Pointy - Oh, this is much weirder than field declarations. :-D

    – T.J. Crowder
    12 hours ago











  • Well field declarations are jarring to me because this is the instance, not the this of the surrounding scope as with object initializers. I guess it's not really "weird" if you think of class declarations as being something akin to macro expansion.

    – Pointy
    12 hours ago











  • @Pointy - Yeah. I think of them as code that's relocated to the beginning of the constructor (just after the super call if it's a subclass). That's what Java does with instance field initializers and instance initialization blocks (and they're literally copied to the beginning of each constructor in Java; thankfully in JavaScript we just have the one). JavaScript took effectively the same approach.

    – T.J. Crowder
    12 hours ago
















17















but still I can't get why it shows 1 instead of undefined.




It's not just you. This is a deep, dark part of the specification. :-)



The key here is that there are two xs. Yes, really. There's the parameter x, and there's the variable x.



A parameter list containing expressions (like f's default value) has its own scope separate from the function body's scope. But prior to parameter lists possibly having expressions, having var x within a function with an x parameter had no effect (x was still the parameter, with the parameter's value). So to preserve that, when there's a parameter list with expressions in it, a separate variable is created and the value of the parameter is copied to the variable at the beginning of the function body. Which is the reason for this seemingly-odd (no, not just seemingly) odd behavior. (If you're the kind who likes to dive into the spec, this copying is Step 28 of FunctionDeclarationInstantiation.)



Since f's default value, () => x, is created within the parameter list scope, it refers to the parameter x, not the var.



So the first solution, [2, 1, 1] is correct, because:




  • 2 was assigned to the var x in the function body. So at the end of the function, the var x is 2.


  • 1 was assigned to y from the var x before x got the value 2, so at the end of the function, y is 1.

  • The parameter x's value has never changed, so f() results in 1 at the end of the function

It's as though the code were written like this instead (I've removed unnecessary parens and added missing semicolons):






console.log(function(param_x, f = () => param_x) 
var var_x = param_x;
var y = var_x;
var_x = 2;
return [var_x, y, f()];
(1));






...I removed var x from the function body, I found that the response changed to #3...




#3 is [2, 1, 2]. That's correct, because when you remove the var x from the function, there's only one x, the parameter (inherited by the function body from the parmeter list). So assigning 2 to x changes the parameter's value, which f returns.



Taking the earier example with param_x and var_x, here's what it looks like if you remove the var x; from it:






console.log(function(param_x, f = () => param_x) 
var y = param_x;
param_x = 2;
return [param_x, y, f()];
(1));






Here's an annotated description of the original code (with the extraneous parentheses removed and missing semicolons added):



// /---- the parameter "x"
// v vvvvvvvvvvv--- the parameter "f" with a default value
console.log(function(x, f = () => x)
var x; // <=== the *variable* x, which gets its initial value from the
// parameter x
var y = x; // <=== sets y to 1 (x's current value)
x = 2; // <=== changes the *variable* x's value to 2
// +---------- 2, because this is the *variable* x
// (1));



Final note regarding your title:




declaring a variable twice in IIFE




The variable is only declared once. The other thing is a parameter, not a variable. The distinction is rarely important...this being one of those rare times. :-)






share|improve this answer




















  • 1





    This is now in my list of "new weird things about JavaScript" alongside the semantics of (not yet really standard) instance property initialization expressions in class declarations.

    – Pointy
    12 hours ago











  • @Pointy - Oh, this is much weirder than field declarations. :-D

    – T.J. Crowder
    12 hours ago











  • Well field declarations are jarring to me because this is the instance, not the this of the surrounding scope as with object initializers. I guess it's not really "weird" if you think of class declarations as being something akin to macro expansion.

    – Pointy
    12 hours ago











  • @Pointy - Yeah. I think of them as code that's relocated to the beginning of the constructor (just after the super call if it's a subclass). That's what Java does with instance field initializers and instance initialization blocks (and they're literally copied to the beginning of each constructor in Java; thankfully in JavaScript we just have the one). JavaScript took effectively the same approach.

    – T.J. Crowder
    12 hours ago














17












17








17








but still I can't get why it shows 1 instead of undefined.




It's not just you. This is a deep, dark part of the specification. :-)



The key here is that there are two xs. Yes, really. There's the parameter x, and there's the variable x.



A parameter list containing expressions (like f's default value) has its own scope separate from the function body's scope. But prior to parameter lists possibly having expressions, having var x within a function with an x parameter had no effect (x was still the parameter, with the parameter's value). So to preserve that, when there's a parameter list with expressions in it, a separate variable is created and the value of the parameter is copied to the variable at the beginning of the function body. Which is the reason for this seemingly-odd (no, not just seemingly) odd behavior. (If you're the kind who likes to dive into the spec, this copying is Step 28 of FunctionDeclarationInstantiation.)



Since f's default value, () => x, is created within the parameter list scope, it refers to the parameter x, not the var.



So the first solution, [2, 1, 1] is correct, because:




  • 2 was assigned to the var x in the function body. So at the end of the function, the var x is 2.


  • 1 was assigned to y from the var x before x got the value 2, so at the end of the function, y is 1.

  • The parameter x's value has never changed, so f() results in 1 at the end of the function

It's as though the code were written like this instead (I've removed unnecessary parens and added missing semicolons):






console.log(function(param_x, f = () => param_x) 
var var_x = param_x;
var y = var_x;
var_x = 2;
return [var_x, y, f()];
(1));






...I removed var x from the function body, I found that the response changed to #3...




#3 is [2, 1, 2]. That's correct, because when you remove the var x from the function, there's only one x, the parameter (inherited by the function body from the parmeter list). So assigning 2 to x changes the parameter's value, which f returns.



Taking the earier example with param_x and var_x, here's what it looks like if you remove the var x; from it:






console.log(function(param_x, f = () => param_x) 
var y = param_x;
param_x = 2;
return [param_x, y, f()];
(1));






Here's an annotated description of the original code (with the extraneous parentheses removed and missing semicolons added):



// /---- the parameter "x"
// v vvvvvvvvvvv--- the parameter "f" with a default value
console.log(function(x, f = () => x)
var x; // <=== the *variable* x, which gets its initial value from the
// parameter x
var y = x; // <=== sets y to 1 (x's current value)
x = 2; // <=== changes the *variable* x's value to 2
// +---------- 2, because this is the *variable* x
// (1));



Final note regarding your title:




declaring a variable twice in IIFE




The variable is only declared once. The other thing is a parameter, not a variable. The distinction is rarely important...this being one of those rare times. :-)






share|improve this answer
















but still I can't get why it shows 1 instead of undefined.




It's not just you. This is a deep, dark part of the specification. :-)



The key here is that there are two xs. Yes, really. There's the parameter x, and there's the variable x.



A parameter list containing expressions (like f's default value) has its own scope separate from the function body's scope. But prior to parameter lists possibly having expressions, having var x within a function with an x parameter had no effect (x was still the parameter, with the parameter's value). So to preserve that, when there's a parameter list with expressions in it, a separate variable is created and the value of the parameter is copied to the variable at the beginning of the function body. Which is the reason for this seemingly-odd (no, not just seemingly) odd behavior. (If you're the kind who likes to dive into the spec, this copying is Step 28 of FunctionDeclarationInstantiation.)



Since f's default value, () => x, is created within the parameter list scope, it refers to the parameter x, not the var.



So the first solution, [2, 1, 1] is correct, because:




  • 2 was assigned to the var x in the function body. So at the end of the function, the var x is 2.


  • 1 was assigned to y from the var x before x got the value 2, so at the end of the function, y is 1.

  • The parameter x's value has never changed, so f() results in 1 at the end of the function

It's as though the code were written like this instead (I've removed unnecessary parens and added missing semicolons):






console.log(function(param_x, f = () => param_x) 
var var_x = param_x;
var y = var_x;
var_x = 2;
return [var_x, y, f()];
(1));






...I removed var x from the function body, I found that the response changed to #3...




#3 is [2, 1, 2]. That's correct, because when you remove the var x from the function, there's only one x, the parameter (inherited by the function body from the parmeter list). So assigning 2 to x changes the parameter's value, which f returns.



Taking the earier example with param_x and var_x, here's what it looks like if you remove the var x; from it:






console.log(function(param_x, f = () => param_x) 
var y = param_x;
param_x = 2;
return [param_x, y, f()];
(1));






Here's an annotated description of the original code (with the extraneous parentheses removed and missing semicolons added):



// /---- the parameter "x"
// v vvvvvvvvvvv--- the parameter "f" with a default value
console.log(function(x, f = () => x)
var x; // <=== the *variable* x, which gets its initial value from the
// parameter x
var y = x; // <=== sets y to 1 (x's current value)
x = 2; // <=== changes the *variable* x's value to 2
// +---------- 2, because this is the *variable* x
// (1));



Final note regarding your title:




declaring a variable twice in IIFE




The variable is only declared once. The other thing is a parameter, not a variable. The distinction is rarely important...this being one of those rare times. :-)






console.log(function(param_x, f = () => param_x) 
var var_x = param_x;
var y = var_x;
var_x = 2;
return [var_x, y, f()];
(1));





console.log(function(param_x, f = () => param_x) 
var var_x = param_x;
var y = var_x;
var_x = 2;
return [var_x, y, f()];
(1));





console.log(function(param_x, f = () => param_x) 
var y = param_x;
param_x = 2;
return [param_x, y, f()];
(1));





console.log(function(param_x, f = () => param_x) 
var y = param_x;
param_x = 2;
return [param_x, y, f()];
(1));






share|improve this answer














share|improve this answer



share|improve this answer








edited 12 hours ago

























answered 13 hours ago









T.J. CrowderT.J. Crowder

699k12312431341




699k12312431341







  • 1





    This is now in my list of "new weird things about JavaScript" alongside the semantics of (not yet really standard) instance property initialization expressions in class declarations.

    – Pointy
    12 hours ago











  • @Pointy - Oh, this is much weirder than field declarations. :-D

    – T.J. Crowder
    12 hours ago











  • Well field declarations are jarring to me because this is the instance, not the this of the surrounding scope as with object initializers. I guess it's not really "weird" if you think of class declarations as being something akin to macro expansion.

    – Pointy
    12 hours ago











  • @Pointy - Yeah. I think of them as code that's relocated to the beginning of the constructor (just after the super call if it's a subclass). That's what Java does with instance field initializers and instance initialization blocks (and they're literally copied to the beginning of each constructor in Java; thankfully in JavaScript we just have the one). JavaScript took effectively the same approach.

    – T.J. Crowder
    12 hours ago













  • 1





    This is now in my list of "new weird things about JavaScript" alongside the semantics of (not yet really standard) instance property initialization expressions in class declarations.

    – Pointy
    12 hours ago











  • @Pointy - Oh, this is much weirder than field declarations. :-D

    – T.J. Crowder
    12 hours ago











  • Well field declarations are jarring to me because this is the instance, not the this of the surrounding scope as with object initializers. I guess it's not really "weird" if you think of class declarations as being something akin to macro expansion.

    – Pointy
    12 hours ago











  • @Pointy - Yeah. I think of them as code that's relocated to the beginning of the constructor (just after the super call if it's a subclass). That's what Java does with instance field initializers and instance initialization blocks (and they're literally copied to the beginning of each constructor in Java; thankfully in JavaScript we just have the one). JavaScript took effectively the same approach.

    – T.J. Crowder
    12 hours ago








1




1





This is now in my list of "new weird things about JavaScript" alongside the semantics of (not yet really standard) instance property initialization expressions in class declarations.

– Pointy
12 hours ago





This is now in my list of "new weird things about JavaScript" alongside the semantics of (not yet really standard) instance property initialization expressions in class declarations.

– Pointy
12 hours ago













@Pointy - Oh, this is much weirder than field declarations. :-D

– T.J. Crowder
12 hours ago





@Pointy - Oh, this is much weirder than field declarations. :-D

– T.J. Crowder
12 hours ago













Well field declarations are jarring to me because this is the instance, not the this of the surrounding scope as with object initializers. I guess it's not really "weird" if you think of class declarations as being something akin to macro expansion.

– Pointy
12 hours ago





Well field declarations are jarring to me because this is the instance, not the this of the surrounding scope as with object initializers. I guess it's not really "weird" if you think of class declarations as being something akin to macro expansion.

– Pointy
12 hours ago













@Pointy - Yeah. I think of them as code that's relocated to the beginning of the constructor (just after the super call if it's a subclass). That's what Java does with instance field initializers and instance initialization blocks (and they're literally copied to the beginning of each constructor in Java; thankfully in JavaScript we just have the one). JavaScript took effectively the same approach.

– T.J. Crowder
12 hours ago






@Pointy - Yeah. I think of them as code that's relocated to the beginning of the constructor (just after the super call if it's a subclass). That's what Java does with instance field initializers and instance initialization blocks (and they're literally copied to the beginning of each constructor in Java; thankfully in JavaScript we just have the one). JavaScript took effectively the same approach.

– T.J. Crowder
12 hours ago














1














The tricky part of that code is that the => function is created as part of a default parameter value expression. In parameter default value expressions, the scope includes the parameters declared to the left, which in this case includes the parameter x. Thus for that reason the x in the => function is in fact the first parameter.



The function is called with just one parameter, 1, so when the => function is called that's what it returns, giving [2, 1, 1].



The var x declaration, as Mr Crowder points out, has the (somewhat weird, at least to me) effect of making a new x in the function scope, into which is copied the value of the parameter x. Without it, there's only the one (the parameter).






share|improve this answer

























  • That still does not explain why removing var x; results in 2, 1, 2 ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms you're right; the var declaration must ... do something but it doesn't seem obvious to me what that is. It's as if the var declaration creates a new x in the function scope, but it clearly gets the value of the parameter x anyway (which I'd expect), leaving the parameter apparently in its own scope.

    – Pointy
    13 hours ago











  • I guess the values are somewhat copied from the default initializers scope to the bodies scope. Im already digging into the spec

    – Jonas Wilms
    13 hours ago











  • It makes sense. As noted in the spec: NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body. thats reasonable.

    – Jonas Wilms
    12 hours ago











  • @Pointy - It's a very deep, dark part of the spec. :-)

    – T.J. Crowder
    12 hours ago















1














The tricky part of that code is that the => function is created as part of a default parameter value expression. In parameter default value expressions, the scope includes the parameters declared to the left, which in this case includes the parameter x. Thus for that reason the x in the => function is in fact the first parameter.



The function is called with just one parameter, 1, so when the => function is called that's what it returns, giving [2, 1, 1].



The var x declaration, as Mr Crowder points out, has the (somewhat weird, at least to me) effect of making a new x in the function scope, into which is copied the value of the parameter x. Without it, there's only the one (the parameter).






share|improve this answer

























  • That still does not explain why removing var x; results in 2, 1, 2 ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms you're right; the var declaration must ... do something but it doesn't seem obvious to me what that is. It's as if the var declaration creates a new x in the function scope, but it clearly gets the value of the parameter x anyway (which I'd expect), leaving the parameter apparently in its own scope.

    – Pointy
    13 hours ago











  • I guess the values are somewhat copied from the default initializers scope to the bodies scope. Im already digging into the spec

    – Jonas Wilms
    13 hours ago











  • It makes sense. As noted in the spec: NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body. thats reasonable.

    – Jonas Wilms
    12 hours ago











  • @Pointy - It's a very deep, dark part of the spec. :-)

    – T.J. Crowder
    12 hours ago













1












1








1







The tricky part of that code is that the => function is created as part of a default parameter value expression. In parameter default value expressions, the scope includes the parameters declared to the left, which in this case includes the parameter x. Thus for that reason the x in the => function is in fact the first parameter.



The function is called with just one parameter, 1, so when the => function is called that's what it returns, giving [2, 1, 1].



The var x declaration, as Mr Crowder points out, has the (somewhat weird, at least to me) effect of making a new x in the function scope, into which is copied the value of the parameter x. Without it, there's only the one (the parameter).






share|improve this answer















The tricky part of that code is that the => function is created as part of a default parameter value expression. In parameter default value expressions, the scope includes the parameters declared to the left, which in this case includes the parameter x. Thus for that reason the x in the => function is in fact the first parameter.



The function is called with just one parameter, 1, so when the => function is called that's what it returns, giving [2, 1, 1].



The var x declaration, as Mr Crowder points out, has the (somewhat weird, at least to me) effect of making a new x in the function scope, into which is copied the value of the parameter x. Without it, there's only the one (the parameter).







share|improve this answer














share|improve this answer



share|improve this answer








edited 13 hours ago

























answered 13 hours ago









PointyPointy

321k45461528




321k45461528












  • That still does not explain why removing var x; results in 2, 1, 2 ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms you're right; the var declaration must ... do something but it doesn't seem obvious to me what that is. It's as if the var declaration creates a new x in the function scope, but it clearly gets the value of the parameter x anyway (which I'd expect), leaving the parameter apparently in its own scope.

    – Pointy
    13 hours ago











  • I guess the values are somewhat copied from the default initializers scope to the bodies scope. Im already digging into the spec

    – Jonas Wilms
    13 hours ago











  • It makes sense. As noted in the spec: NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body. thats reasonable.

    – Jonas Wilms
    12 hours ago











  • @Pointy - It's a very deep, dark part of the spec. :-)

    – T.J. Crowder
    12 hours ago

















  • That still does not explain why removing var x; results in 2, 1, 2 ...

    – Jonas Wilms
    13 hours ago











  • @JonasWilms you're right; the var declaration must ... do something but it doesn't seem obvious to me what that is. It's as if the var declaration creates a new x in the function scope, but it clearly gets the value of the parameter x anyway (which I'd expect), leaving the parameter apparently in its own scope.

    – Pointy
    13 hours ago











  • I guess the values are somewhat copied from the default initializers scope to the bodies scope. Im already digging into the spec

    – Jonas Wilms
    13 hours ago











  • It makes sense. As noted in the spec: NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body. thats reasonable.

    – Jonas Wilms
    12 hours ago











  • @Pointy - It's a very deep, dark part of the spec. :-)

    – T.J. Crowder
    12 hours ago
















That still does not explain why removing var x; results in 2, 1, 2 ...

– Jonas Wilms
13 hours ago





That still does not explain why removing var x; results in 2, 1, 2 ...

– Jonas Wilms
13 hours ago













@JonasWilms you're right; the var declaration must ... do something but it doesn't seem obvious to me what that is. It's as if the var declaration creates a new x in the function scope, but it clearly gets the value of the parameter x anyway (which I'd expect), leaving the parameter apparently in its own scope.

– Pointy
13 hours ago





@JonasWilms you're right; the var declaration must ... do something but it doesn't seem obvious to me what that is. It's as if the var declaration creates a new x in the function scope, but it clearly gets the value of the parameter x anyway (which I'd expect), leaving the parameter apparently in its own scope.

– Pointy
13 hours ago













I guess the values are somewhat copied from the default initializers scope to the bodies scope. Im already digging into the spec

– Jonas Wilms
13 hours ago





I guess the values are somewhat copied from the default initializers scope to the bodies scope. Im already digging into the spec

– Jonas Wilms
13 hours ago













It makes sense. As noted in the spec: NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body. thats reasonable.

– Jonas Wilms
12 hours ago





It makes sense. As noted in the spec: NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body. thats reasonable.

– Jonas Wilms
12 hours ago













@Pointy - It's a very deep, dark part of the spec. :-)

– T.J. Crowder
12 hours ago





@Pointy - It's a very deep, dark part of the spec. :-)

– T.J. Crowder
12 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55560027%2fdeclaring-a-variable-twice-in-iife%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

На ростанях Змест Гісторыя напісання | Месца дзеяння | Час дзеяння | Назва | Праблематыка трылогіі | Аўтабіяграфічнасць | Трылогія ў тэатры і кіно | Пераклады | У культуры | Зноскі Літаратура | Спасылкі | НавігацыяДагледжаная версіяправерана1 зменаДагледжаная версіяправерана1 зменаАкадэмік МІЦКЕВІЧ Канстанцін Міхайлавіч (Якуб Колас) Прадмова М. І. Мушынскага, доктара філалагічных навук, члена-карэспандэнта Нацыянальнай акадэміі навук Рэспублікі Беларусь, прафесараНашаніўцы ў трылогіі Якуба Коласа «На ростанях»: вобразы і прататыпы125 лет Янке МавруКнижно-документальная выставка к 125-летию со дня рождения Якуба Коласа (1882—1956)Колас Якуб. Новая зямля (паэма), На ростанях (трылогія). Сулкоўскі Уладзімір. Радзіма Якуба Коласа (серыял жывапісных палотнаў)Вокладка кнігіІлюстрацыя М. С. БасалыгіНа ростаняхАўдыёверсія трылогііВ. Жолтак У Люсiнскай школе 1959

Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп