1

The following code

'use strict';

function blah() {

    if (1 ==21) {
    }
    else {
        var i = 10;
        function inner() {
            console.log(i);
        }
    }
}

Produces the following error:

SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.

How can I write my function inner such that it has access to my variable 'i'? According to strict mode I need to move the function to the top but at this point 'i' has not been declared

deltanovember
  • 40,595
  • 61
  • 158
  • 240
  • 1
    That code (specifically the function declaration within a block) isn't strictly valid in any version of ECMAScript. It only works at all because all major browsers implement extensions to ECMAScript to cope with this particular case. – Tim Down Aug 02 '12 at 23:31

4 Answers4

4

Since var i will be hoisted to the top of function blah's scope anyway, you could do this:

'use strict';

function blah() {
    var i;
    function inner() {
        console.log(i);
    }

    if (1 ==21) {
    }
    else {
        i = 10;
    }
}​
2

Where does inner() need to be accessible from? Will this work for your purposes?:

var inner = function () { ... };
JMM
  • 24,450
  • 3
  • 46
  • 55
1

It has been declared, since the var declares the variable for the entire function, not for the block.

Neil
  • 52,766
  • 8
  • 57
  • 71
1

The inner function must be declared as a function expression, like so:

var inner = function () {
    console.log(i);
};
Sal Rahman
  • 4,433
  • 2
  • 28
  • 40