-
-
Save dbrgn/8784608 to your computer and use it in GitHub Desktop.
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
> var name = 'World!'; | |
undefined | |
> (function () { | |
... if (typeof name === 'undefined') { | |
..... console.log('Goodbye ' + name); | |
..... } else { | |
..... console.log('Hello ' + name); | |
..... } | |
... })(); | |
Hello World! | |
undefined |
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
> var name = 'World!'; | |
undefined | |
> (function () { | |
... if (typeof name === 'undefined') { | |
..... var name = 'Jack'; | |
..... console.log('Goodbye ' + name); | |
..... } else { | |
..... console.log('Hello ' + name); | |
..... } | |
... })(); | |
Goodbye Jack | |
undefined |
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
> 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 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
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 undefinedname
variable gets defined after the(function(){
part. And because of this it always ends in the Goodbye part.