Why second console.log output is the function body rather than 20?

74 Views Asked by At
(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

There are 2 best solutions below

0
Nicholas Tower On BEST ANSWER

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.

(function b() {
  'use strict';
  console.log(b);
  b = 20;         // Throws an exception
  console.log(b); // Never gets to here
})();

0
Ian On

Let's break down what's happening in your code:

(function b() {
  console.log(b); // This refers to the function itself
  b = 20; // Here you're trying to assign a value to the function, but it won't work as expected
  console.log(b); // This still refers to the function itself
})();
  1. The IIFE (Immediately Invoked Function Expression) is defined with the name b. Inside the function, the identifier b refers to the function itself.
  2. The first console.log(b) outputs the function definition, as b refers to the function at this point.
  3. The line b = 20; is encountered. Here's where things get interesting: since b was declared as the function itself, this line tries to assign the value 20 to the function b. However, functions in JavaScript are objects, and you can assign properties to them, but this doesn't change their behavior as a function.
  4. The second 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 change b still refers to the function, 20 in this b inside.