I have the following javascript.
var f = function() { ... };
if (x === 1) {
// redefine f.
f = function() {
...
};
}
Is that code valid ?
In other words can I redefine a javascript function inside an if statement where I actually write the code.
I am worried because of this:
Function declarations inside if/else statements?
Yes you can do that.
is not a function declaration, it is a function expression (assigned to
f), so the problems mentioned in the other question don’t apply here.Only variable and function declarations are hoisted.