(function b() {
console.log(b);
b = 20;
console.log(b);
})();
I wrote this JavaScript IIFE.
The first console.log
logs the function body.
Then the b
variable is created with value 20
.
The second console.log
also logs the function body.
Why not 20
?
2
Answers
Because
b
is constant and cannot be assigned to. You’re in non-strict mode, so the assignment just silently does nothing, but if you use strict mode you will get an error, highlighting the problem.Let’s break down what’s happening in your code:
b
. Inside the function, the identifierb
refers to the function itself.console.log(b)
outputs the function definition, asb
refers to the function at this point.b = 20;
is encountered. Here’s where things get interesting: sinceb
was declared as the function itself, this line tries to assign the value20
to the functionb
. However, functions in JavaScript are objects, and you can assign properties to them, but this doesn’t change their behavior as a function.console.log(b)
still refers to the function, so it outputs the same function definition as before.In essence, the assignment
b = 20
doesn’t changeb
still refers to the function,20
in thisb
inside.