Skip to content

Instantly share code, notes, and snippets.

@dbrgn
Created February 3, 2014 14:18
Show Gist options
  • Save dbrgn/8784608 to your computer and use it in GitHub Desktop.
Save dbrgn/8784608 to your computer and use it in GitHub Desktop.
> var name = 'World!';
undefined
> (function () {
... if (typeof name === 'undefined') {
..... console.log('Goodbye ' + name);
..... } else {
..... console.log('Hello ' + name);
..... }
... })();
Hello World!
undefined
> var name = 'World!';
undefined
> (function () {
... if (typeof name === 'undefined') {
..... var name = 'Jack';
..... console.log('Goodbye ' + name);
..... } else {
..... console.log('Hello ' + name);
..... }
... })();
Goodbye Jack
undefined
> var name = 'World!';
undefined
> (function () {
... if (typeof name === 'undefined') {
..... console.log('Goodbye ' + name);
..... } else {
..... var name = 'Jack';
..... console.log('Hello ' + name);
..... }
... })();
Goodbye undefined
undefined
@tschortsch
Copy link

Good one ;) But here comes the Mr. Know-It-All explanation:
JavaScript defines it's locally scoped variables (defined with var) always at the top of a block. In examples 2 and 3 an undefined name variable gets defined after the (function(){ part. And because of this it always ends in the Goodbye part.

@dbrgn
Copy link
Author

dbrgn commented Feb 3, 2014

@tschortsch Yes, that's the right explanation, but no excuse for such a batshit crazy language design :)

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