Function declarations and variable declarations is always moved ("hoisted") invisibly to the top of their containing SCOP E by the JavaScript interpreter.
Example1:
var foo = 1; function Bar () { if (! Foo) { var foo = ten; } // Ten } Bar ();
Example2:
var a = 1; function B () { = ten; return ; function A () {} } b (); // 1
Example3:
var x = 1; // 1 if (true) { var x = 2; // 2 } // 2
Example4:
function foo () { var x = 1; if (x) { (function () { var x = 2; // Some other code } ()); } // x is still 1. }
Named Function Expressions
You can give names to functions defined on function expressions, with syntax like a function declaration. This does does it a function declaration, and the name is not brought to scope, nor is the body hoisted. Here's some code to illustrate what I mean:
Example 5:
Foo ();//TypeError "Foo is not a function"Bar ();//validBaz ();//TypeError "Baz is not a function"Spam ();//referenceerror "spam is not defined" varFoo =function() { };//anonymous function expression (' foo ' gets hoisted) functionBar () {};//function declaration (' Bar ' and the function body get hoisted) varBaz =functionSpam () {};//named function expression (only ' Baz ' gets hoisted)foo ();//validBar ();//validBaz ();//validSpam ();//referenceerror "spam is not defined"
Example 6:
// 5 var function () {Console.log (4);}; function getName () {Console.log (5);}; GetName (); // 4
Example 7:
functionFoo () {getName=function() {Console.log (1); }; return This; } foo.getname=function() {Console.log (2); }; Foo.prototype.getName=function() {Console.log (3); }; varGetName =function() {Console.log (4); }; functionGetName () {Console.log (5); }; Foo.getname (); //2GetName ();//4Foo (). GetName ();//1GetName ();//1 NewFoo.getname ();//2 NewFoo (). GetName ();//3 New NewFoo (). GetName ();//3
JS Scope and variable elevation