Flosculus
Flosculus

Reputation: 6946

Javascript Statement Order of Execution

var confirm = confirm('Are you sure?');

I've just tested this statement, and I was given an error stating that confirm is not a function.

I detected immediately that the variable name was overwriting it. However my question is why?

I know that functions are first class, and that declaring a variable of the same name as function will overwrite it within the relative scope. But my confusion comes from what I thought was an order of execution from "right to left", I.E. the function call is made before the destination is determined.

Does the variable become defined in this case before the function call?

Upvotes: 5

Views: 930

Answers (1)

Phylogenesis
Phylogenesis

Reputation: 7880

Due to JavaScript's variable hoisting:

function myFunction() {
    // ...
    var confirm = confirm('Are you sure?');
    // ...
}

becomes :

function myFunction() {
    var confirm;
    // ...
    confirm = confirm('Are you sure?');
    // ...
}

You will need to do the following to enforce your meaning:

function myFunction() {
    // ...
    var confirm = window.confirm('Are you sure?');
    // ...
}

Upvotes: 7

Related Questions