File scoped functions in ES6


I am exploring ES2015 and for it, I use the ‘recommended’ eslintrc file to try and follow MDGs style guide. Now since there is no more var foo = function() {} for file scope, I would have thought the natural thing to do would be const foo = function() {}. However, the linter complains because this is an expression, not a declaration as detailed here. So I guess my question really is, can I have a declarative function definition that is still file scoped in ES2015?


Yes, function declarations are always file scoped.


but writing function foo() {} makes it global, doesn’t it?


Also, this is one of those rules which is designed for code consistency rather than to make your coded “better.” From the link you posted: “There is really no correct or incorrect choice here, it is just a preference.” Definitely feel free to set this rule differently if you prefer the other style.


Thanks for your answer. Still, what I would like to understand here is, how would you define a file scoped function using the declarative style? Would you mind posting two function definitions, one for a global, one for a local function using declarative style, so I can see how it’s done?


I don’t think so. I just tried it with code, and function foo() {} does not appear to be global. So you’d have to declare a global foo = function() {} or foo = function foo() {}. Maybe double check my result, but I think that’s correct.


yes, you’re right! got it and thanks.


You just define it with function foo() {}. The Meteor build tool wraps the code of each file in a Immediately-invoked function expression. Therefore a function declaration is always scoped to the file. A function declaration has basically the same meaning as:

var foo = function () {


(In addition it gets hoisted to the top of the file)

If you remove the var keyword, the function becomes global when declared in the app context or package global when declared in package context.