javascript variable hoisting .

javascript variable hoisting .

hey guys have a look at the below code ::

  1.   var i = 1;
  2.             $('document').ready(function(){
  3.                 str = funk();
  4.                 console.log(str);
  5.                     var elem = $('ul li:nth-child('+ i +')');
  6.                     elem.on('click' , function(){
  7.                         console.log('logged');
  8.                         funk();
  9.                     });
  10.             });
  11.             var funk = function() {
  12.                   return i < 5 ? i++ : i = 0 ;
  13.             }

see how the funk() function gets called before it is defined . now if i change the order to as follows .

  1. 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(); ??