1

just wondering why this boolean isn't changing each time I call the function in Codepen with babel.

let status = true;

let statusChange = () => {
  status = !status;
  return `new status: ${status}`;
}

console.log(statusChange());
console.log(statusChange());
console.log(statusChange());
console.log(statusChange());
console.log(statusChange());

You should see the console logs alternate between true and false. Am I going insane here..?

Pocketninja
  • 395
  • 1
  • 12
  • 1
    It works if you chose another name than `status`... – le_m Jan 22 '18 at 00:16
  • lol thank you, so the 1 word I choose has now wasted about 1 hour of my life. I will never use that word again :-P How do I close this as complete..? Do you now put this in the Answer area..? So this can be completed? Cheers – Pocketninja Jan 22 '18 at 00:19
  • If you do typeof status before it is even set, it returns "string" very strange. – Pocketninja Jan 22 '18 at 00:36

1 Answers1

1

Babel transforms your code into this:

var status = true;

var statusChange = function statusChange() {
  status = !status;
  return "new status: " + status;
};

console.log(statusChange());
console.log(statusChange());
console.log(statusChange());
console.log(statusChange());
console.log(statusChange());

As you can see, let status = true has been changed into var status = true. Unfortunately, there is a big difference between let and var which Babel didn't consider here:

At the top level of programs and functions, let, unlike var, does not create a property on the global object. MDN

Unfortunately, there is already a property status on the global object (i.e. window.status). Thus, with var, you run into this issue described here: Boolean variable returns as string from javascript function

le_m
  • 19,302
  • 9
  • 64
  • 74
  • I think this overrides the other question as a more complete answer now :-) – Pocketninja Jan 22 '18 at 00:41
  • @Pocketninja I have full sympathies for any developer who goes crazy over this ;) - Actually, I wonder if this is a bug within babel or rather codepen... – le_m Jan 22 '18 at 00:44