Why can’t I assign values to a variable inside a named function expression with the same name?
Asked Answered
A

1

10

This is a named function expression with the name test. Inside, I assign 123 to a variable, also named test. Then test is logged. The function prints its body in the console, but not 123. What is the reason for such behavior?

(function test() {
  test = 123;
  console.log( test );
}());

Where does my explanation of function execution fail?

  1. Start of function execution: test is a local variable that references the function itself
  2. Local variable test is reassigned to number 123
  3. console.log(test) shows the number 123.
Aney answered 3/6, 2014 at 17:33 Comment(9)
#6319335Cunha
I'm not sure we can consider this an exact duplicate. In this case there is an assignment, not simply var test; as in the linked question.Stoppage
@dandavis If you still here, in the comment to Kodlee's answer you said "the name of the function is a "var" to the function...". In the same manner as arguments are declared? If that's the case, is the function name somehow protected then? You can change the value of arguments thought they are "pre-declared".Forcible
@Teemu: i'm not sure exactly how the name works low-level. the function name is slightly special no doubt since it seems to resist direct clobbering, but i don't know about "protected"; you can still "var test=123;" inside the function, which makes sense. An ecmaScript spec check would probably explain the phenomenon we're experiencing.Necrophobia
Possible duplicate of Javascript - Hoisting IssueSmalley
@VLAZ is there a burnination for the [function-declaration] and [function-expression] tags? I find them quite useful - and at least the latter still applies to this question.Jackinthepulpit
@Jackinthepulpit [function-expression] no but [function-declaration] is misapplied. It's about forward declarations of functions a-la C style where the signature is declared then the body separately. Rather than the JS notion where it's a hoisted statement. I've been removing expression tags where it seemed to not really be relevant. But seems it was relevant here. My bad.Scamp
@Scamp I think it would have been better to just make the tag description of [function-declaration] say what it means in JS, where [hoisting] is the default. Or if you insist, re-tag to [js-function-declaration].Jackinthepulpit
@Jackinthepulpit I appreciate the feedback. I created [javascript-function-declaration] and tried to give it a meaningful wiki. I will work towards applying it to questions I removed function-declaration from.Scamp
S
7

I believe this piece of the ecma spec explains this behavior. This relates specifically to named Function Expressions

The production

FunctionExpression : function Identifier ( FormalParameterListopt ) { FunctionBody }

is evaluated as follows:

  1. Let funcEnv be the result of calling NewDeclarativeEnvironment passing the running execution context’s Lexical Environment as the argument
  2. Let envRec be funcEnv’s environment record.
  3. Call the CreateImmutableBinding concrete method of envRec passing the String value of Identifier as the argument.
  4. Let closure be the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in funcEnv as the Scope. Pass in true as the Strict flag if the FunctionExpression is contained in strict code or if its FunctionBody is strict code.
  5. Call the InitializeImmutableBinding concrete method of envRec passing the String value of Identifier and closure as the arguments.
  6. Return closure.

The use of CreateImmutableBinding when creating the scope of a named Function Expression, creates the identifier (in this case test) as an immutable variable. That is why assignment to it does not change its value.

Stoppage answered 3/6, 2014 at 18:9 Comment(7)
Related would be this discussion of why this is done #15130004Stoppage
I wonder if the binding is immutable why this code doesn't throw in strict mode? (function test() { "use strict"; test = 123; console.log( test); }())Raffinate
@YuryTarabanko: It does throw an Unhandled Error: Invalid assignment in strict mode. Maybe try (function(){ "use strict"; (function test() { test = 123;}()); }())Jackinthepulpit
OK, why this code would print 123 in console? (function test() { var test = 123; console.log(test)}()); Does CreateImmutableBinding forbid only variable changing, but not variable redefinition?Aney
@RomanBelyaev Once you add var to your test you create a local test instead of trying to re-assign the immutableStoppage
@YuryTarabanko: That's indeed a bug in Chrome. They throw correctly when assigning to arguments.Jackinthepulpit
In the 9th edition of the ECMA-262 spec this behavior is in section 14.1.21 RS: Evaluation, in the 10th edition it currently is in 14.1.22 RS: Evaluation. Should we update this answer to the current spec?Jesusa

© 2022 - 2024 — McMap. All rights reserved.