Are variables declared and assigned in an "if" statement visible only within that "if" block or within the whole function?
Am I doing this right in the following code? (seems to work, but declaring "var structure" multiple times seems awkward) any cleaner solutions?
function actionPane(state) { if(state === "ed") { var structure = { "element" : "div", "attr" : { "class" : "actionPane" }, "contains" : [{ "element" : "a", "attr" : { "title" : "edit", "href" : "#", "class" : "edit" }, "contains" : "" }, { "element" : "a", "attr" : { "title" : "delete", "href" : "#", "class" : "delete" }, "contains" : "" }] } } else { var structure = { "element" : "div", "attr" : { "class" : "actionPane" }, "contains" : [{ "element" : "a", "attr" : { "title" : "save", "href" : "#", "class" : "save" }, "contains" : "" }, { "element" : "a", "attr" : { "title" : "cancel", "href" : "#", "class" : "cancel" }, "contains" : "" }] } } return structure; }
Should you define a variable inside IF statement? Honestly, there's no right or wrong answer to this question. JavaScript allows it, so you can make your decision from there.
Scope of a Variable in If Statement So, anything declared in an if block has the same scope as anything declared outside the block. Variables are not checked at compile-time, which is why other languages throw an exception.
JavaScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be defined anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
In JavaScript, scopes are created by code blocks, functions, modules. While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules. Scopes can be nested. Inside an inner scope you can access the variables of an outer scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With