Reputation: 6759
I'm using Codacy for my project and i'm getting a warning saying that I shouldn't use variables which I declare later, which is quite logical. However, this should work fine for constructors.
This is my main file structure:
/* Export */
module.exports = myObject; // this line
/* Import */
var otherObject = require('./otherObject');
function myObject(input) {
}
myObject.prototype = {
}
Could any problems occur by exporting before the object constructor declaration? Should I move the export line below the constructor like?
Upvotes: 1
Views: 1684
Reputation: 111404
This will put the correct function in module.exports
because of function hoisting:
module.exports = myObject;
function myObject(input) {
}
This will put undefined
in module.exports
(with no error) because of variable hoisting:
module.exports = myObject;
var myObject = function (input) {
};
This will raise ReferenceError: myObject is not defined
exception because of the let
scoping rules:
module.exports = myObject;
let myObject = function (input) {
};
and so will this becasue of const
scoping:
module.exports = myObject;
const myObject = function (input) {
};
On the other hand, all of those will work the same and as expected if you put module.exports = myObject;
at the end - which you'll have to do anyway if you follow e.g. the Airbnb coding style:
or if you use some linter rules, e.g. this ESLint rule:
Disallow Early Use (no-use-before-define)
In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it’s possible to use identifiers before their formal declarations in code. This can be confusing and some believe it is best to always declare variables and functions before using them.
In ES6, block-level bindings (let and const) introduce a “temporal dead zone” where a ReferenceError will be thrown with any attempt to access the variable before its declaration.
Upvotes: 5