DaeYoung
DaeYoung

Reputation: 1229

invoke javascript expression

I have tried below two javascript functions in chrome via developer tool however I thought second function would be invoked when js interpreter reaches it but didn't. Not sure why.

var x = function() { console.log("probably not invoked."); }

var x = function() { console.log("probably invoked."); };

x(); // I had to do this to invoke the function

The reason behind of testing this is I was using XmlHttpRequest first time while reading property name status of the object I ran into a piece of code as below I was told that onreadystatechange function pointer will be executed so I thought having semicolon on anonymous function would be executed when js interpreter reaches it?

function makeRequest() {
    .....
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            document.getElementById("status").innerHTML = (xhr.status == 200) ? "status good" : "status bad";
        }
    };
    xhr.send();

Upvotes: 0

Views: 82

Answers (1)

Quentin
Quentin

Reputation: 943999

The XMLHttpRequest object will look for a function stored in onreadystatechange and call it when the ready state changes.

It is the event firing that triggers the function being called, not the assignment itself.

This is akin to

document.body.onclick = function () { alert("You clicked!"); };

The semi-colon on the end is just the regular semi-colon that you (should) put after every JavaScript statement.

Upvotes: 4

Related Questions