Welcome Guest! (App Version 3.1)

websitnero logo name

Hoisting

Variable Hoisting

If a variable is declared inside a function along with the 'var' keyword, then it automatically becomes a local variable. In such a condition, though the variable might be assigned value somewhere deep inside the function, but automatically it is declared to the top of function.

Look at the following example to get deeper understanding:

Example

<script>

var a = 10; 

function alpha(){
  alert(a); //variable hoisting puts a to be 'undefined'
  alert(b); //variable hoisting puts b to be 'undefined'
  var a = 15
  var b = 20;
  alert(a);
  alert(b);
}

alpha();

</script>

Functional Hoisting

If a function is written inside another function then too it holds the ticket to 'hoisting', this time 'functional hoisting'. This means the function can be called even before it is defined. Magic? No, because just like variable the function declaration is automatically moved to the top of the 'functional scope'.

Look at the following example to get deeper understanding:

Example

<script>

var a = 10; 

function alpha(){

  //fn1(); //hoisting not done in functional expression so will give error
  fn2(); //hosting takes places in function declration so works fine 

  var fn1 = function(){
    alert('hi');
  }

  function fn2(){
    alert('hello');
  }
	
}

alpha();

</script>
WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.