3

I faced with this weird problem that the function variable in JS is not writable in some case.

function a(){
  a=1
  console.log(a)
}
a() // output 1



(function a(){
  a=1
  console.log(a)
})() // output a function 'a'



var b=function a(){
  a=1
  console.log(a)
}
b()  // output is also a function 'a'
laishere
  • 95
  • 7
  • 1
    yes, things go weird when you try and *misuse* a programming language :p I have no answer, but a question - why would you ever want to do such a thing? – Jaromanda X Apr 23 '19 at 02:20
  • 3
    @Jaromanda X well, I think everything should be explainable, a bug or by design. I just want to make sense of it. – laishere Apr 23 '19 at 02:31

1 Answers1

4

From this source: Variable hoisting inside IIFE (lazy parsing)

The situation you are experimenting is related to the immutability/mutability of the identifier/name of a function when it is a function expression (identifier inmutable) and a function declaration (identifier mutable).

In your first example, there is a function declaration with identifier a (mutable), so you are overwriting it inside the method and the output is the result of that overwriting:

function a()
{
    console.log("Without overwrite:", a);
    a = 1; // The identifier `a` is mutable!
    console.log("After overwrite:", a);
}

a();
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

On the second and third examples, you are using function expressions where the identifier a is not mutable (i.e, read-only). So, you can't change it and the output of the console is the function definition:

(function a()
{
    a = 1; // The identifier `a` is not mutable!
    console.log(a);
})();

var b = function aa()
{
    aa = 1; // The identifier `aa` is not mutable!
    console.log(aa);
}

b();
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Shidersz
  • 16,846
  • 2
  • 23
  • 48