0

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();

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.