0
function outer(x) {
    function inner(y) {
        if (y) console.log(y);
        else console.log(42);
    }
    inner(x + 1);
}
outer(5); // expect a logging of '6'
inner(); // expect a Reference Error

I know what it is supposed to do and I expect it to do just that but are there any cross-browser quirks or side effects I should be aware of when declaring inner functions.

[Edit]

By safe I meant is it possible they pollute global namespaces or are not treated as being local to the function they were declared in.

[/Edit]

Raynos
  • 166,823
  • 56
  • 351
  • 396

3 Answers3

1

Afaik no. IE has problems with named function expressions like:

var inner = function inner2() {

}

but everything else should be fine.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Does that named function expression when used as an inner function hoist the scope of the funcion `inner` to global namespace? – Raynos Jan 24 '11 at 10:15
  • @Raynos: No, IE just creates two functions instead of one, but they stay in the same scope. – Felix Kling Jan 24 '11 at 10:20
  • Are there any strange side effects of using `var name = function name() { ... }` Where your using the same name for the function declaration & function expression in IE? – Raynos Jan 24 '11 at 10:27
  • @Raynos: Not 100% sure. The worse thing is that IE would still create two functions but one name would shadow the other one. – Felix Kling Jan 24 '11 at 10:49
0

That's regular ECMAScript syntax. It allows for closures and "inner functions". Statements (function declarations and var) within a function are scoped within that function.

In your example, the function inner exists only within outer's scope; anything else than a Reference Error when trying to call inner() should be considered a "quirk".


UPDATE: Found a question probably related to this one.

Community
  • 1
  • 1
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
0

I'm not sure what you mean by "safe". In your example there is no way to invoke inner() from outside of outer(). If "safe" - means only function visibility, then your are right, it's safe.

Alexandr
  • 9,213
  • 12
  • 62
  • 102