javascript variable hoisting .
hey guys have a look at the below code ::
- var i = 1;
- $('document').ready(function(){
- str = funk();
- console.log(str);
- var elem = $('ul li:nth-child('+ i +')');
- elem.on('click' , function(){
- console.log('logged');
- funk();
- });
- });
- var funk = function() {
- return i < 5 ? i++ : i = 0 ;
- }
see how the funk() function gets called before it is defined . now if i change the order to as follows .
- var i = 1;
var funk = function() {
return i < 5 ? i++ : i = 0 ;
}
$('document').ready(function(){
str = funk();
console.log(str);
var elem = $('ul li:nth-child('+ i +')');
elem.on('click' , function(){
console.log('logged');
funk();
});
});
things work out better . but i taught my 1st snippet of code should have worked fine because js has variable hoisting , which means during runtime or execution , the fucntion definition of funk() would automatically change and would move above
str = funk(); ??