I saw the code below that someone posted. I'm confused about what it logs. It logs variable a
the function, not 200. Why?
var a = 1;
(function a() {
a = 200;
console.log(a)
})()
I saw the code below that someone posted. I'm confused about what it logs. It logs variable a
the function, not 200. Why?
var a = 1;
(function a() {
a = 200;
console.log(a)
})()
Because the function being immediately invoked is named, and that name cannot be reassigned to refer to something else directly inside the IIFE.
Any named function expressions will exhibit this behavior as well. A function expression whose function is named
a
will mean thata
directly inside the function will always refer to the function itself, even if you try to reassign it.You can make the error explicit if you use strict mode:
Having a named function expression is a bit like having
except trying to reassign it will only throw in strict mode.
Specifically, I believe the ECMAScript 5 specification for this behavior is in SetMutableBinding:
But directly inside a function, the function name binding is not mutable - see Function Definition: