以下のJavaScriptにはバグがある。
print(1);if( true !== true ){ return; }; print(2);
SpiderMonkeyで実行すると、return文がSyntax errorだと言われる。
js> if( true !== true ){ return; }; print( 1 ); typein:11: SyntaxError: return not in function: typein:11: if( true !== true ){ return; }; print(1); typein:11: .....................^ js>
関数の中ではないところでreturn文は書いてはいけないらしい。
ここまではよいのだが、重要なのはprint(1);もprint(2);も実行されないということである。
これはJavaScriptの独特なところらしい。
例えば、shで同じことをやってみる。
echo "1"; return; echo "2"
$ sh ./a.sh 1 ./a.sh: line 1: return: can only `return' from a function or sourced script 2
このようにecho "1"もecho "2"も実行されている。
perlではどうなるだろうか?
print "1"; return; print "2";
$ perl ./a.pl Can't return outside a subroutine at ./a.pl line 1. 1
1つ目だけ実行された!
うーむ。この統一感のなさ。スクリプト言語怖い。
他の言語でも試したいが時間がないのでここまで。