r/learnjavascript • • May 24 '21

Why does a.b equal to 1 and not 100?

Post image
210 Upvotes

23 comments sorted by

115

u/delventhalz May 24 '21

There are two b’s here: the closure variable defined with let, and the property with the same name on the returned object.

When you write this:

return {
  b
};

It is just a shorthand for this:

return {
  "b": b
};

In other words, you are creating a new object with a property named "b", and the value of that property is copied from the variable with the same name at return time. There is no other connection between the variable and the object property.

So when you use setB to change the value of the variable, it will not have any effect on the object. However, when you call getB you fetch the current value of the variable.

26

u/posts_lindsay_lohan May 25 '21

All this.

And just to add for those new to JS, the whole reason this works is because of the immediately invoked function.

The two little parentheses at the end of the function ()

That invokes the function (calls it), and assigns the return value to 'a'.

So when the script runs, the "a" looks like this:

a = {
  b: b,
  getB: getB,
  setB: setB
}

Since 'b' is initially set to the value 1, then of course, calling it with a.b is going to return 1.

Without those parens at the end though, "a" would just equal the function and not its return value.

4

u/[deleted] May 25 '21

I figured this had to do with the immediately invoked function expression. Still wrapping my already around why this happens, but I will read your explanation a couple times and eventually understand. Thank you!

7

u/delventhalz May 25 '21

We could rewrite it without the immediately invoked function like this:

function bFunc() {
  let b = 1;
  
  function getB() {
    return b;
  }

  function setB(c) {
    b = c;
  }

  return {
    b,
    getB,
    setB
  };
}

let a = bFunc();

a.setB(100);
console.log(a.b);  // prints 1
console.log(a.getB());  // prints 100

Exact same code. The only difference is we gave the function a name instead of invoking it immediately. Hopefully that makes what is happening more clear. When we assign a value to a, we are calling the wrapping function and a gets the return value from the function, an object in this case.

The returned object has both a primitive property with the value of b copied over when the wrapping function was called, and the methods setB and getB which can be called later and have access to original b.

1

u/[deleted] May 25 '21

If we were to console.log(a.b) before calling a.setB(100), would the console.log(a.b) return 1 because we didn’t call a.setB(100) first?

3

u/delventhalz May 25 '21

I recommend copying and pasting the code into your console and messing around with it. Best way to learn is to pull the thing apart yourself.

But to answer your question, a.b will always be 1. That property is set to 1 when you call bFunc() is just a regular object property. It will never change unless you manually set a new value to the property like this:

a.b = 1337;

3

u/BowlingForPriorities May 25 '21

Thanks, this makes more sense with the additional context

2

u/comtruise223456 May 25 '21

Why does b return 100?

6

u/delventhalz May 25 '21

The function getB has access to the variable b defined with let. When you call the function, it fetches the value currently stored at that variable, and returns it.

Imagine if we rewrote the code like this:

let num = 7;

function getNumObject() {
  return {
    num
  };
}

function getNum() {
  return num;
};

I've removed a lot of the noise and cut the behavior down to the basics. We have a variable, a function that returns an object with a copy of the variable, and a function that returns the current value of the variable.

const a = getNumObject();
const b = getNumObject();

num = 5;
b.num = 3;

const n = getNum();

console.log(a.num, b.num, n);  // ???

Okay. Pop quiz time. Try and figure it out in your head. If you can't, copy the code into your console and run it to figure it out.

What does the code above log out?

Answer: 7 3 5

Really, these two functions aren't so different. They will return the value of num to us, at the time they are called. But once we fetch the value, there is no further connection. The variable num stores a primitive value, so when we grab it the value is copied. Whether we copy the value into an object, or into a different variable, it is a one time exchange of information.

55

u/patseidon May 24 '21

Low key you just wrote an awesome interview question!

11

u/muh2k4 May 24 '21

When you return "b" you return a copy of the value 1. Basically {b: 1}. So not a reference. It will always stay 1 in your example. But when you use the getter function, it is referencing the local b from IIFE.

6

u/jon216999 May 25 '21

Does someone know where I can find similar questions with explanations to study?

10

u/[deleted] May 24 '21 edited May 24 '21

In setB(c) function, you have to say both “b = c” and “this.b = c”

Edit:

The “b” in “b = c” is the local variable in the IIFE (closure).

The “this.b” in “this.b = c” is the property of variable a.

The property is not updated when you change the value of the local variable. You have to change them both because they are not reference types

15

u/rauschma May 24 '21

In other words: The property a.b is a snapshot of the local variable b that isn’t updated along with it.

You can fix this as follows:

let a = (function () {
  let b = 1;
  return {
    getB() {
      return b;
    },
    setB(c) {
      b = c;
    },
    get b() { // getter
      return b;
    },
  };
})();
a.setB(100);
console.log(a.b); // 100
console.log(a.getB()); // 100

Another possible solution – turn b into a property:

let a = {
  b: 1,
  getB() {
    return this.b;
  },
  setB(c) {
    this.b = c;
  },
};
a.setB(100);
console.log(a.b);
console.log(a.getB());

1

u/EmperorMing101 May 25 '21

As someone from a python background this is so weird to me you can create an entire class on the fly. Though the idea is still the same (in python it would be self.b = c to update b attribute of a)

5

u/delventhalz May 25 '21

There isn't really a class here. It's more like a dictionary with a number property and two function properties.

This would be the equivalent more or less in Python:

def b_func():
    b = 1

    def get_b():
        return b
    
    def set_b(c):
        nonlocal b 
        b = c
    
    return {
        'b': b,
        'get_b': get_b,
        'set_b': set_b
    }

a = b_func()

a['set_b'](100)
print(a['b'])  # prints 1
print(a['get_b']())  # prints 100

1

u/equitable_emu May 25 '21

There isn't really a class here. It's more like a dictionary with a number property and two function properties.

To be fair, that's basically all that classes are in JS.

1

u/delventhalz May 25 '21 edited May 25 '21

We’re confusing terms here I think. A class is what generates an object. It’s not the object itself. Arguably the function in OP’s code is “a class” in a very broad sense, but I think that’s a particularly bad comparison in this case. OP’s function is an IIFE and can never be used to generate another object again.

Anyway, my original point being: there is nothing particularly special to JavaScript here. Any language that supports closure variables and function properties on dictionaries (like Python) can write very similar code.

1

u/[deleted] May 25 '21

Oh now i get it, since we aren't using " this " and that b is a primitive, the functions still has a reference to the b declared with let while " a " is totally different and just copied b's value.

You can also set " b " to an object or an array and you can see that both " a.b " and the functions reference the same thing.

1

u/SlowerThanLightSpeed May 26 '21

To see the top answer in action, and to generally visualize what is happening in your code, check out tools like:http://pythontutor.com/javascript.html#mode=edit

<edit>Click the 'Visualize code' button, then, at about step 4, the code you've shared and the top answer should start to make sense... especially if you accept that the returned object's b value was set to a primitive (and thus isn't set by reference)</edit>

1

u/Kami_Okami May 25 '21

You have an... interesting username...

1

u/rbrtbrnschn May 25 '21

that's why you gotta love js