1

I am new to javascript and want to understand the difference between the two :

Hello

<script type="text/javascript">
    function pageOnloadHandler() {
        var a = 5;
        var b = 6;
        document.write(a + b);
   }
 `window.onload = pageOnloadHandler();`

Output is : Hello 11

But when I write, window.onload = pageOnloadHandler;

Output is : 11

  • Hello – user3687376 May 07 '16 at 07:57
  • 5
    Possible duplicate of [In JavaScript, does it make a difference if I call a function with parentheses?](http://stackoverflow.com/questions/3246928/in-javascript-does-it-make-a-difference-if-i-call-a-function-with-parentheses) – Nirpendra Patel May 07 '16 at 08:05

1 Answers1

0

It's because when document.write() is executed after document is loaded it overwrites the whole document

When you type this:

Window.onload = pageOnloadhandler();

you pass the result from the function and not the function itself so window.onload would be undefined as your function doesn't have a return value

But when you use

Window.onload = pageOnloadhandler;

You give the window.onload object the function itself which is then executed onload