skip to Main Content
(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


  1. 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
    })();
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search