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;
}
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:
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.
ECMAScript 2015 (ES6) includes two new keywords that finally allow JavaScript to accomplish proper block scoping without the need to use work-around, colloquial syntax:
In Javascript, all variables are either
Yes. A cleaner solution might be to build a base class of
structure
, and modify what is different in each case.JavaScript has no "block scope", it only has function scope - so variables declared inside an if statement (or any conditional block) are "hoisted" to the outer scope.
This actually paints a clearer picture (and comes up in interviews, from experience :)
Function scope, in JavaScript, typically refers to closures.
The inner scope of the function has access to the environment in which it is contained, but not the other way around.
To answer your second question, optimisation can be achieved by initially constructing a 'minimal' object which satisfies all conditions and then augmenting or modifying it based on particular condition(s) which has/have been satisfied.
Variables declared inside the if statement will be available outisde as long as they reside in the same function.
In your case, the best way would be to declare structure and then modify the parts of the object that differ in either case: