Skip to content
Advertisement

How to use strict mode and not get an error in JSlint

Looking at all the information out there on JSlint (eg. here or here), the discussion goes something like this

Always use strict mode since it catches many more errors. All you have to do is put ‘use strict’ at the top of your code. That’s it! Couldn’t be easier… Except when JSlint complains and tells you to put it in function scope, then you have to put all of your code inside a giant function.

I have hundreds of functions written in javascript and at a minimum the <body>calls a callback function on load so I am trying to wrap my head around how I am supposed to put all my functions inside another function but still ensure that the <body> element can still pierce the outer function and call my functions with the internal scope.

Can someone tell me how I would implement strict mode for something like so

function foo(){
    "use strict"; /* Approach 1: Putting inside every function */
                  /* Extremely tedious and ugly */
    $('#example').text('Hello '+ bar());
}

function bar(){
    "use strict"; /* Approach 1: Putting inside every function */
                  /* Extremely tedious and ugly */
    return 'Beautiful';
}

function fooBar (){
    "use strict"; /* Approach 2: Putting once at the top of an outer function */
    
    /* But now how does <body> call this function? */
    function foo(){
        "use strict";
        $('#example').text('Hello '+ bar());
    }

    function bar(){
        "use strict";
        return 'Beautiful';
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="foo();">
<p id='example'>
</p>
</body>

Advertisement

Answer

In modern JavaScript, inline handlers should be avoided whenever possible since they require global pollution, require ugly quote escaping with some arguments, and have absurd scope chain rules. So, try removing the inline handlers and put your JavaScript into an IIFE, which can be made strict:

(() => {
  "use strict";

  function foo() {
    $('#example').text('Hello ' + bar());
  }

  function bar() {
    return 'Beautiful';
  }
  window.addEventListener('DOMContentLoaded', foo);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <p id='example'>
  </p>
</body>

If you have any other inline handlers similar to <body onload="foo();">, I’d highly recommend refactoring them out.

Advertisement