Skip to content

Instantly share code, notes, and snippets.

@npup
Created December 21, 2010 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npup/750095 to your computer and use it in GitHub Desktop.
Save npup/750095 to your computer and use it in GitHub Desktop.
Variabler i scope
function apa1() {
var david = 'david';
console.log('%s', david);
}
apa1(); // david
function apa2() {
var david = 'david';
console.log('%s, %s', david, petter);
return;
var petter;
}
apa2(); // david, undefined
function apa3() {
var david = 'david';
console.log('%s, %s, %s', david, petter, urban);
return;
var petter, urban = 'urban';
}
apa3(); // david, undefined, undefined
function apa4() {
var david = 'david';
console.log('%s, %s, %s, %s', david, petter, urban, ingen);
return;
var petter, urban = 'urban';
}
try {
apa4(); // ReferenceError på "ingen"
}
catch (e) {
console.log('apa4() => %s', e.message);
}
function apa5() {
console.log(inner_fd());
return;
function inner_fd() {
return 'a function declaration';
}
}
apa5(); // works, inner_fd is hoisted
function apa6() {
console.log('==>'+inner_fd());
console.log('==>'+inner_fe);
return;
function inner_fd() {
return 'a function declaration';
}
var inner_fe = function () {
return 'a function expression';
}
}
apa6(); // inner_fd works, inner_fe CAN BE REFERENCED
function apa7() {
console.log('==>'+inner_fd());
console.log('==>'+inner_fe);
console.log('==>'+inner_fe());
return;
function inner_fd() {
return 'a function declaration';
}
var inner_fe = function () {
return 'a function expression';
}
}
try {
apa7(); // // inner_fd works, inner_fe can be referenced, but is not initialized and cannot be called (is undefined)
}
catch(e) {
console.log('apa7 => %s', e.message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment