Why does it display undefined ?

 function rush (filename){ (function(){ var res = filename.split("."); var b = res[res.lenght - 1]; return b; })(); } alert(rush("work.tt")); 

Thanks in advance!

  • one
    You can find out why inside the function the code is wrapped in a self-invoking function? - Alexey Shimansky
  • I thought maybe the problem is closure, I don’t understand why it loses the result - lesha310392
  • @ lesha310392, with such errors, step-by-step debugging helps well. - Grundy
  • It may be worth noting the answer as true (the jackdaw on the left, next to the voices). - val

2 answers 2

Why does it display undefined?

Because the rush function returns nothing.

If you remove all unnecessary function, you can write this:

 function rush (filename){ (function(){...})(); } 

This clearly shows the absence of return . Therefore, the result of this function is always undefined .

Head- on solution - add return

 function rush(filename) { return (function() { var res = filename.split("."); var b = res[res.lenght - 1]; return b; })(); } console.log(rush("work.tt")); 

When adding, you will notice that it still does not work. Since there is a typo

 lenght -> length 

 function rush(filename) { return (function() { var res = filename.split("."); var b = res[res.length - 1]; return b; })(); } console.log(rush("work.tt")); 

Now you can see that the self-calling function is not needed

 function rush(filename) { var res = filename.split("."); var b = res[res.length - 1]; return b; } console.log(rush("work.tt")); 

Also, to get the last element of the array, you can use the pop function

 function rush(filename) { return filename.split(".").pop(); } console.log(rush("work.tt")); 

     function rush (filename){ var res = filename.split("."); return res[res.length - 1]; } alert(rush("work.tt"));