Search code examples
javascriptecmascript-6es6-modulesjshintiife

How to fix 'Function declarations should not be placed in blocks' error in Javascript es6?


After a long time without using Javascript, I try to do understand what is es6, modules and iife.

So I make a little piece of code :

{
    'use strict';

    let version = '1.0.0';

    function init(){
        /* ... */
    }

    window.Test = {
        version: version,
        init: init
    };
}

And jshint returns this error : Function declarations should not be placed in blocks. Use a function expression or move the statement to the top of the outer function.

But, if I use the es5 format (function(){...}()) there is no problem. So what did I misunderstand ?

Furthermore, if someone have some time to answer some questions more :

  • 'use strict' is necessary or redundant ?
  • I use an iife, but is it a module too ? (I think, I have very misunderstand this part)
  • window.Test is it the best way to export my variable Test ?

Thank you in advance for your answers, Sam.

EDIT : a good video to understand module : https://www.youtube.com/watch?v=qJWALEoGge4


Solution

  • And jshint returns this error: Function declarations should not be placed in blocks. Use a function expression or move the statement to the top of the outer function.

    That means that jshint doesn't understand ES6. Or you might need to configure it so that it does.

    'use strict' is necessary or redundant?

    The one you used here doesn't work, as directive prologues can only be placed in functions (or on the begin of a module or script), but not in a block.

    I use an iife, but is it a module too?

    No, you are not using an IIFE here. It's just a block, but that's ok.

    It does implement the module pattern ("create an object with access to privately-scoped internals"), but it is not an ES6 module.

    window.Test is it the best way to export my variable Test?

    No, I would recommend declaring it with var.