Last active
December 24, 2015 00:40
-
-
Save pamelafox/6718591 to your computer and use it in GitHub Desktop.
A surprising use of JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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? |
Oh god. Ow.
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.)
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
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 definescoordinates
variable, then I think most of them believe the first is the case, while if they realize it definescoordinates
andy
, then I think most of them believe the second is the case.