javascript variable scope in the IF statement

1) Variables are visible for the whole function scope. Therefore, you should only declare them once.

2) You should not declare the variable twice in your example. I’d recommend declaring the variable at the top of the function, then just setting the value later:

function actionPane(state) {
    var structure;
    if(state === "ed") {
        structure = {    
            ...

For excellent feedback on JavaScript, I highly recommend using JSLint by Douglas Crockford. It will scan your code for common errors, and find suggestions for cleanup.

I also recommend reading the small book JavaScript: The Good Parts. It contains a lot of tips for writing maintainable JS code.

Leave a Comment