Which first: func defs or global vars?


I tend to avoid referencing implicitly global variables in my function definitions wherever possible, but the more Javascript I read, the more it appears that JS developers don’t adhere to that convention.

When your functions reference externally-declared global variables, which is considered better form in JavaScript?:

A. initialize variables -> define functions -> script
B. define functions -> initialize variables -> script
C. shut up and get coding

I believe that in Python, it doesn’t make a practical difference. However, for legibility, I would prefer to initialize the global variables before defining my functions and then I’d follow the definitions with the actual script.


Shut up and get coding, after you read this:


Reading now. Thanks!


In LSTHW I go with ES6 and actually completely ignore function and var for this reason. In fact, that 2ality article is a good description of all the scoping issues that just go away if you avoid these two. Basically, define all your functions with const fat-arrow style:

const myStuff = (arg1, arg2) => {
   let result = arg1 + arg2;
   return result;

The fat arrow => has correct this semantics and just works better is slightly subtle ways. The above can even be converted to a single line without a return:

const MyStuff = (arg1, arg2) => arg1 + arg2;

Making it ideal for a lot of your callback situations, especially with Promises too.

Use let for all your variables in all scopes to get correct scoping AND protection from shadow variables.

Do that and then you only have to deal with function when you make async functions, in the new classes style, and with yield/function* situations. I believe function inside classes has a corrected this semantics so you don’t need to worry then either.

There ya go. My whole book I basically teach a stripped down safer JS using this, although most likely I’ll find oodles of other landmines I didn’t anticipate.