/**
* Variable Hoisting
*/
// Variable declarations are hoisted
function test0() {
x = 5;
var x=2;
console.log(x);
// interpreted as
// var x;
// x = 5;
// x = 2;
}
// Function statements (as a whole) are hoisted,
// unlike variables which only get their declaration hoisted
function test1() {
myStatement(); // this works
myExpression(); // this will not work
function myStatement() {};
var myExpression = function () {};
}
// javascript engine will hoist variable declarations to the top of the function or scope, and in doing so function declarations will beat out variables.
function test2() {
var myName;
function myName() {};
console.log(typeof myName); // function
/**/
/*
// but when variable is defined, it wins
var myName = "tim";
function myName(){};
console.log(typeof myName); // string
/**/
}
// functions defined in blocks (not functions) will be hoisted out
// this is the nature of scope and no block-level scoping
function test3(declareFunction) {
declaredFunction(); // "Oh yeah... I'm declared"
if (declareFunction) {
// declaration is moved to the top of test3's scope
function declaredFunction() {
console.log("Oh yeah.. I'm declared");
}
var declaredFunction = function() {
console.log("Expression declared!");
}
declaredFunction(); // "Expression declared!"
}
declaredFunction(); // "Expression declared!"
}
//test0();
//test2();
test3(true);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.