javascript assingment and hoisting
by jiggle
JavaScript
var x=5,y=6,z;
console.log(x,y,z);
x=y++; //what will be x and y ?
console.log('x',x);
console.log('y',y);
z=++y;
console.log('z',z);
console.log('hoisting');
var x = 5;
function c() {
if (typeof(x) === 'undefined') {
var x = 10;
console.log(x);
}
console.log(x);//what would be the result ?
}
c();
console.log(x);//what will x be here
console.log('hoisting 2');
var x=5;//x is already defined and assigned with value 5 and is available in Global scope.
function d( ) {
var x; // variable x get hoisted to the top.
if (typeof(x) === 'undefined') {//therefore, here it will be undefined.
x = 11;//assigning value 10
console.log(x); //x will be 10
}
console.log(x);// x will be 10 , value of x will be 10 inside the function scope.
}
d();
console.log(x); // here the value of x will be still 5. Since it has its own value available in the global scope.
console.log('hoisting 3');
declareMe();//calling function
fnExpression();//calling function
//Creating a function by declaration.
function declareMe(){
console.log("this is function declaration" + testHoist); //testHoist will be undefined because declareMe is run before the assignment further down, only the variable names will be hoisted.
}
//creating a function by expression.
var fnExpression = function(){
console.log("this is function expression");
}
var testHoist='testing I\'m hoisted';