1

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?

Community
  • 1
  • 1
Zo72
  • 14,593
  • 17
  • 71
  • 103
  • @Kriem I think you are mistaken this is a different question. It concerns about hoisting and redefining and being in an if statemetn – Zo72 Feb 18 '13 at 14:17
  • I see that now. Apologies. I was too quick with my assumption. – Kriem Feb 18 '13 at 14:18
  • @Kriem no worries... it happens... many thanks. – Zo72 Feb 18 '13 at 14:19
  • @Kriem can you take out the message "This question may already have an answer here" from the top... as we agree it's not correct – Zo72 Feb 25 '13 at 09:50

1 Answers1

1

Yes you can do that.

f = function() { 
   ...
};

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • thanks very much would you mind elaborate your answer. I want to use this approach but I am still worried about how hoisting might affect this... – Zo72 Feb 18 '13 at 14:16
  • There is not much more to say. Only function and variables declarations are hoisted. The only declaration you have is `var f` at the beginning of your code. Assignments only take place when they are reached in the code. – Felix Kling Feb 18 '13 at 14:18
  • yes but I define function f() again (inside the if) how do you know that that does not cause trouble ? – Zo72 Feb 18 '13 at 14:20
  • You are not defining a function `f` (you never did). You are assigning a value to the variable `f` which happens to be a function. Functions are first class objects in JavaScript, so it's the same as assigning any other value, e.g. `f = 42;`. – Felix Kling Feb 18 '13 at 14:21
  • If you don't know about the differences between a function declaration and a function expression, have a look at this question: http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip. – Felix Kling Feb 18 '13 at 14:30