JSFiddle - React, Tailwind, and code Playground
by Jason Aden
JavaScript
/**
* 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!"
}
//test1();
//test2();
//test3(true);