-3

Why is the result of alert undefined but not 6?I think the function addLoadEvent works well,and so does the alert

function addLoadEvent(func){
  var oldonload = window.onload;
  if(typeof oldonload != 'function'){
    window.onload = func;
  }else{
    window.onload = function(){
    oldonload();
    func();
    }
  }
}
function a(){
  return 6;
}
alert(addLoadEvent(a))
MTCoster
  • 5,868
  • 3
  • 28
  • 49
  • 1
    If you could, please edit *your actual code* as text into your question - images of code *alone* are [tedious and difficult](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) to work with and debug. It forces those who would otherwise love to help you to [transcribe your image](https://idownvotedbecau.se/imageofcode) first, which is a waste of time. – CertainPerformance Dec 04 '18 at 08:58
  • `addLoadEvent` doesn't actually return anything, so this is why you are getting `undefined`. For the effect you want, you need to either to do `alert(6)` inside `a()` (you're not actually using the return value). Either that or put the alert inside `addLoadEvent` – Robin Zigmond Dec 04 '18 at 09:08

1 Answers1

0

addLoadEvent has no return statement, so it returns undefined.

It is a that returns 6, but you aren't logging the return value of a (which isn't available until after the load event fires, which is too late to capture it at the point you are trying to).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335