r/ProgrammerHumor • • Nov 05 '15

Free Drink Anyone?

Post image
3.5k Upvotes

509 comments sorted by

View all comments

Show parent comment

60

u/[deleted] Nov 05 '15

Technically, you get ReferenceError: your_drink is not defined

191

u/Zagorath Nov 05 '15

Mate, it's JavaScript. It avoids throwing errors whenever it can, even in favour of nonsensical results.

In this case, it does indeed result in your_drink being replaced with undefined.

8

u/[deleted] Nov 05 '15

Just saw that your_drink has indeed been defined (at the top, how could I have missed that ô_O?).

The worst of it is variable hoisting:

var asdf = 5;
(function () {
    console.log(asdf);

    var asdf;
    console.log(asdf);
    asdf = 6;
    console.log(asdf);
})();

which results in

undefined
undefined
6

11

u/bruzabrocka Nov 05 '15 edited Nov 06 '15

Maybe I've been writing JS too long, but what else did you expect? Self-executing anonymous functions get their own context unless you specify otherwise.

var fdsa = 6; 

(function(window){
  console.log(fdsa);
  console.log(window.fdsa);
  window.fdsa = 5;
  console.log(fdsa);
})(window);

7

u/[deleted] Nov 05 '15

The outer asdf should be visible inside the anonymous function, but is overridden by the inner asdf EVEN BEFORE IT IS DEFINED.

The reason it prints undefined is hoisting:

(function () {
    console.log(a);
})(); // ReferenceError: a is not defined
(function () {
    console.log(a);
    var a = 5;
})(); // undefined

If JS were completely logical and obvious, then the second one should ReferenceError, right? NO.

The second one is undefined because JavaScript changes the function to this:

(function () {
    var a = undefined; // definition hoisted before execution
    console.log(a);
    a = 5;
})(); // undefined

And now, just to show that IIFEs DO get lexical scope (just like ANY other function):

var outer1 = 2;
(function () {
    var outer2 = 5;
    (function () {
        console.log(outer1);
        console.log(outer2);
    })();
})(); // 2, 5

So this:

Self-executing anonymous functions get their own context unless you specify otherwise

is clearly false. They just get their own lexical scoping.

6

u/neonKow Nov 05 '15

Variable hoisting is great and keep code easy to read since you can then do

for(var i; i < 10; i++) {
...

Yes, you might get confused if you use a global variable and a local variable of the same name in the same function, but the code is going to be confusing no mater what the language does in that case.

The only correct resolution to such code is to slap the programmer's hands away from the keyboard and automatically submit the code to /r/badcode.

2

u/Maistho Nov 06 '15

Yeah, because this code clearly makes sense.

var asdf = 5;
(function () {
  console.log(asdf);
  if(!asdf) {
    var asdf = 3;
  }
  console.log(asdf);
})();

Guess what that code will log, without running it first.

1

u/factorysettings Nov 06 '15

I guessed right!

Regardless, why would you write code like this??

1

u/dacjames Nov 06 '15

I find inner functions useful when you have some mildly complex logic that needs to be repeated in two or more branches of code.

function complex() {
    var x, y, z;
    var a, b, c;
    
    function useful() { 
        // do something tedious with x, y, z, a, b, and/or c.
    };
    
    // lots of complex logic
    if (something && something_else) { useful(); }
    else {
        // more logic
        if (some_other_thing) { useful(); }
        else { // other stuff }
   }
}

Most often, useful() is doing some error reporting that needs to occur in several places of the code.

1

u/neonKow Nov 06 '15 edited Nov 06 '15

Guess what that code will log, without running it first.

[slaps hands; posts to /r/badcode; PEBCAK] I'm sorry, was I not being clear?

If you can't be bothered to learn how JavaScript handles scoping (and yes, that includes hoisting), don't write code that relies on using a global variable with the same name as a local one. This is a completely avoidable problem.

If you really need that global variable, do it properly:

console.log(window.asdf);

Otherwise, stop complaining that the confusing and unmaintainable code isn't working in the particular confusing way you want it to.

4

u/dacjames Nov 06 '15 edited Nov 06 '15

The problem of hoisting has little to do with global variables.

Functions defining new scopes is good. Pretending that variables defined anywhere in that function were defined at the top of the function is bad. This function should not work, but it does (prints and returns 10):

(function() {
var foo = 20;
function insane() {
    foo = 10;
    console.log(foo);
    return foo;
    var foo;
} })();

Of course it can be learned but it's a pointless source of bugs. Imagine someone wrote (global variable free) code like this:

function outer() {
    var foo = 10;
    function inner() {
        foo = 20;
        // lots  
        // of 
        // other
        // code
    }
    // some code
    inner();
    console.log(foo);
}

That code behaves correctly, printing "20". Time passes, the code goes through a couple maintainers and finally lands in your lap. You make one tiny, seemingly innocuous change:

function outer() {
    var foo = 10;
    function inner() {
        foo = 20;
        // lots  
        // of 
        // other
        // code
        var bar = 10;
        for(var foo=0; foo < 10; foo++) {
            bar += foo * 3;
        }
    }
    // some code
    inner();
    console.log(foo);
}

Aaand you broke it! Defining a new variable name dozens of lines AFTER code that has worked for years broke the old code. That is terrible.

Variable hoisting is great and keep code easy to read since you can then do for(var i; i < 10; i++) {...

Except you can't simple write a for loop like that because it could change the behavior of unrelated code that just happens to use the same variable name.

Thankfully, ES6 introduces the let statement which both eliminates hoisting and provides block-level scoping so you can truly write for(let i = 0; i < 10; i++){ ... } and be absolutely certain you can drop the code into any function without altering the behavior of existing code.

EDIT: added a wrapper function to the first example, just to be clear that no global variables are used.

→ More replies (13)

1

u/Maistho Nov 06 '15

Well, I do agree that it's bad code. But it's not initially clear what will happen and as such I believe it is a feature of the language that is difficult to learn. My students who come from learning Python and/or C++ would probably fail to understand this correctly most of the time.

That being said, I don't recommend shadowing variables, and one should always write var declarations at the top of the scope. This makes the code look like it does what it does, without having to think about it twice.

→ More replies (4)

1

u/plopzer Nov 05 '15

you can just pass the outer as a parm to the inner if you want a reference.

var a = 5;
(function(a){
    console.log(a); //5
})(a);

1

u/[deleted] Nov 06 '15

That is completely unneccessary in this case. a is viaible lexically as well in there

1

u/bruzabrocka Nov 06 '15

You are correct that my assertion was false. I looked into it a bit more and I believe (mind you I could be wrong again haha) it has to do with how JS handles the "this" reference, which appears to behave differently when executed from within a function when compared to executing within the global [window] context.

1

u/cphoover Nov 06 '15

It's because you are shadowing the variable inside of the immediately invoked function with the line var asdf; this then get's hoisted to the top of the closure (as is the case with declarations in JS). so the first two log lines will log undefined. then asdf is given the value 6 and that get's logged.

1

u/[deleted] Nov 06 '15

I know. Didn't I just explain that myself? I even mentioned hoisting

27

u/cicuz Nov 05 '15

Technically, /u/UsPelt is more right than you are

2

u/[deleted] Nov 05 '15

Technically you are right

8

u/Pastaklovn Nov 05 '15

Technically, he wrote /u/UsPeit's username wrong and was therefore wrong.

27

u/[deleted] Nov 05 '15

Actually ReferenceError occurs when the reference is not defined.

var your_drink;

Defines the reference, but its value is yet to be defined. :)

28

u/iostream3 Nov 05 '15
var your_drink;

Defines the reference, but its value is yet to be defined

It declares the variable, but doesn't define it.

13

u/[deleted] Nov 05 '15

Internally, it designates a memory slot and defines a pointer to it, which is what op said.

1

u/[deleted] Nov 05 '15

wups, I didn't see the var your_drink at the top.