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 followin
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.
if(true) {
var foo = "bar";
}
alert(foo); // "bar"
This actually paints a clearer picture (and comes up in interviews, from experience :)
var foo = "test";
if(true) {
alert(foo); // Interviewer: "What does this alert?" Answer: "test"
var foo = "bar";
}
alert(foo); // "bar" Interviewer: Why is that? Answer: Because JavaScript does not have block scope
Function scope, in JavaScript, typically refers to closures.
var bar = "heheheh";
var blah = (function() {
var foo = "hello";
alert(bar); // "heheheh"
alert(foo); // "hello" (obviously)
});
blah(); // "heheheh", "hello"
alert(foo); // undefined, no alert
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.