Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Last active December 24, 2015 00:40
Show Gist options
  • Save pamelafox/6718591 to your computer and use it in GitHub Desktop.
Save pamelafox/6718591 to your computer and use it in GitHub Desktop.
A surprising use of JS
// Pop quiz!
// 1. What will x and y be in this code?
(function() {
var x = 5;
var y = 10;
var coordinates = x, y;
console.log('First');
console.log(x);
console.log(y);
})();
// 2. And what about in this code?
(function() {
var x = 5;
var y = 10;
function makeCoords() {
var coordinates = x, y;
console.log('Second');
console.log(x);
console.log(y);
}
makeCoords();
})();
// Now check your answers in repl.it!
// Finally, what do you think a new programmer thought would happen, when they wrote line 19?
@kn
Copy link

kn commented Sep 26, 2013

First - 5 ,10
Second - 5, undefined

I think it depends on how new programmers interpret var coordinates = x, y; statement. If they think it just defines coordinates variable, then I think most of them believe the first is the case, while if they realize it defines coordinates and y, then I think most of them believe the second is the case.

@aredridel
Copy link

Oh god. Ow.

@IvanVergiliev
Copy link

Judging by the variable names, I'd say a novice was trying to achieve something like a Python tuple that holds both x and y. In this case, they definitely wouldn't expect any change to the globally defined x and y.
(I thought the same at the beginning, but that was because I saw operator comma in there - which is a whole different source of confusion.)

@torifat
Copy link

torifat commented Sep 26, 2013

We can rewrite the first one as -

var x = 5;
var y = 10;
var coordinates = x;
var y; // It will be hoisted in this scope so redefining does nothing
console.log('First');
console.log(x);
console.log(y);

And, the second one as -

var x = 5;
var y = 10;

function makeCoords() {
    var coordinates = x;
    var y; // But here it is a new declaration in this function scope
    console.log('Second');
    console.log(x);
    console.log(y);
}

IMO, If you teach someone hoisting and scope then (s)he should be able to figure it out 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment