2
(function () {
    "use strict";


    function initialize() {
        myList = ['one', 'two', 'three'];
    }

    function displayList() {
        var i, n;
        for (i = 0, n = myList.length; i < n; i += 1) {
            alert(myList[i]);
        }
    }
    initialize();
    displayList();

})();

if not using var, the myList variable will supposedly be created as a globle variable. Either way, the code should be running. What is wrong with the code??

Joshua
  • 305
  • 4
  • 16

3 Answers3

7
myList = ['one', 'two', 'three'];

In strict mode, you are not allowed to create global variables in this way.

From official Mozilla documentation -

First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). Assignments which would accidentally create global variables instead throw in strict mode:

"use strict";

mistypedVaraible = 17; // throws a ReferenceError

This works -

(function () {
    "use strict";

    var myList;

    function initialize() {
        myList = ['one', 'two', 'three'];
    }

    function displayList() {
        var i, n;
        for (i = 0, n = myList.length; i < n; i += 1) {
            alert(myList[i]);
        }
    }

    initialize();
    displayList();
})();
MD Sayem Ahmed
  • 28,628
  • 27
  • 111
  • 178
0

You cannot set global variables like that when in strict mode.

You'll have to do

(function () {
    "use strict";

    var myList;

    function initialize() {
        myList = ['one', 'two', 'three'];
    }

    function displayList() {
        var i, n;
        for (i = 0, n = myList.length; i < n; i += 1) {
            alert(myList[i]);
        }
    }
    initialize();
    displayList();

})();
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
0

By using "use strict" you're limiting yourself to strict mode (which is a good thing), but that means you can't just use a variable that hasn't been set yet.

If you want to define myList as a global variable, you'll have to do that before the function starts, so at the top of the script put: var myList;

Stephan Muller
  • 27,018
  • 16
  • 85
  • 126