Skip to content

Instantly share code, notes, and snippets.

@wakhub
Created July 15, 2012 05:35
Show Gist options
  • Save wakhub/3115177 to your computer and use it in GitHub Desktop.
Save wakhub/3115177 to your computer and use it in GitHub Desktop.
JavaScript Hoisting Test
// Ref) http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
if (typeof print === 'undefined') print = console.log;
var a;
function f() {
if (0) {
var a = 456;
}
print(a);
};
function f2() {
if (0) {
a = 456;
}
print(a);
}
function f3() {
if (0) {
(function(){
var a = 456;
})();
}
print(a);
}
function f4() {
print(a);
var b = a;
var a = b;
}
a = 123;
f(); // undefined
a = 123;
f2(); // 123
a = 123;
f3(); // 123
a = 123;
f4(); // undefined
local a
function f()
if false then
local a = 456
end
print(a)
end
function f2()
if false then
a = 456
end
print(a)
end
function f3()
if false then
(function()
local a = 456
end)()
end
print(a)
end
function f4()
print(a)
local b = a
local a = b
end
a = 123
f() -- 123
a = 123
f2() -- 123
a = 123
f3() -- 123
a = 123
f4() -- 123
use strict;
use warnings;
my $a;
sub f {
if (0) {
my $a = 456;
}
print "$a\n";
}
sub f2 {
if (0) {
$a = 456;
}
print "$a\n";
}
sub f3 {
if (0) {
(sub {
my $a = 456;
})->();
}
print "$a\n";
}
sub f4 {
print "$a\n";
my $b = $a;
my $a = $b;
}
$a = 123;
f(); # 123
$a = 123;
f2(); # 123
$a = 123;
f3(); # 123
$a = 123;
f4(); # 123
a = None
def f():
if 0:
a = 456
print a
def f2():
global a
if 0:
a = 456
print a
def f3():
if 0:
def _f():
a = 456
_f()
print a
def f4():
print a
b = a
a = b
a = 123
#f() # UnboundLocalError: local variable 'a' referenced before assignment
a = 123
f2() # 123
a = 123
f3() # 123
a = 123
#f4() # UnboundLocalError: local variable 'a' referenced before assignment
a = nil
def f
if false
a = 456
end
puts a
end
$global_a = nil
def f2
if false
$global_a = 456
end
puts $global_a
end
def f3
if false
def _f()
a = 456
end
_f()
end
puts a
end
def f4
puts a
b = a
a = b
end
a = 123
f() # nil
$global_a = 123
f2() # 123
a = 123
#f3() # undefined local variable or method `a' for main:Object (NameError)
a = 123
#f4() # undefined local variable or method `a' for main:Object (NameError)
var a = 0;
def f() = {
if (false) {
var a = 456;
}
println(a);
}
def f2() = {
if (false) {
a = 456;
}
println(a);
}
def f3() = {
if (false) {
(() => {
var a = 456;
})();
}
println(a);
}
def f4() = {
println(a);
var b = a;
// var a = b; // error: forward reference extends over definition of variable b
}
a = 123;
f(); // 123
a = 123;
f2(); // 123
a = 123;
f3(); // 123
a = 123;
//f4(); // error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment