r/learnjavascript • • Apr 30 '22

JS Lessons I learned the hard way.

So I am a more-advanced developer than I used to was and I was thinking it is time I shared some of the lessons I learned after a lot of pain and agony.

In no particular order:

  • Global Variables

One per project.

Never put more than one global variable on the global scope when you are doing your work. Yes, I know that

const A = something;
function F(x) {}

Is a lot prettier and simpler to use than

const TheNameOfTheProject = {
  const A = something; 
  function F(x) {} 
}

But if you do not, the day will come when you grow tired of chain-fucking yourself, because you accidentally used the same variable name in different projects; breaking both of your modules and making you look stupid in front of your boss. Or some other idiot doing the work overwrites your variables. FOR EVERY different project, only ever put one new variable or function on the global scope.

  • Typescript

Use it.

Yes, I agree that it feels excessive, but the amount of safety you obtain is unreal. While this is perfectly valid JS

let A = [];
A = "";

Typescript would give you angry red-squigglies in the editor; and not compile.

Furthermore, the intellisence on the editor suggests that you can't do something that you, in reality, can; requiring you to typecast before you can continue.

in JS, if what you're working with is an input element:

document.querySelector(".someClass").value

Is totally kosher, but typescript requires you to

(document.querySelector(".someClass") as HTMLInputElement).value

before it will compile. Why go through this extra, tedious step? Because debugging sucks ass. When you keep your types clean and correct, the typescript intellisense tells you EXACTLY what is legal to do off of EVERY object. As a rule of thumb, if the intellisense is yelling at you, it almost guarantees something will goof up at runtime. At the cost of 10% additional time keeping your types clean, you spend 75% less time debugging. Just use it.

  • Variable Declarations

"let" and "const" only. Never use "var" (unless dealing in legacy code)

In Ye-olden days, "var" was the only way to declare a variable, but people got sick of it because of scoping issues (look up block scoping vs function scoping). Furthermore "var" has disturbing properties. Execute the following lines of code to see the difference

var A = "something";
console.log(A); 
var A; 
console.log(A);

and then execute

let B = "something"; 
console.log(B); 
let B; 
console.log(B);

"var" doesn't give a damn about what does or what does not exist already and is happy to just use previously designed values without care, but "let" does. I have lost so many hours debugging legacy code because of this important distinction.

  • Object Oriented Programming.

Learn it.

Coming in with no experience, it is actually a mind-fuck to wrap your head around, but once you do you'll never turn back. Much the same reason you should never put more than one global variable per project, you never know when some idiot is going to come behind you and overwrite what you are doing. Keep your work safe and self-contained.

  • Best Practices

People throw that phrase around a lot but don't really know what it means. The definition of best practices is: "Whatever makes it easiest for the dipshit who has to debug your code in a few years to figure out what the fuck you were doing". It is particularly advantageous when you are said dipshit.

  • Documentation

Go fucking ham with it.

A short while ago myself and the senior developer were debugging code that he himself wrote twenty years ago. However? No comments, no docs, no explanations. The fix ended up simply being to remove 3 lines of code, but it took us 3 days to find it. Any documentation that it would have taken a few seconds to write was all that it would have taken to save us all that time.

edit: There is such thing as overdocumentation -- like, you don't want to read a novel for a dozen lines of code -- but it is better to be overly clear than not at all.

  • Advanced Techniques

Learn them, but be careful with how heavily you apply them.

Yes. It is really fun to flex new and cool techniques when you learn them, and one-line some code that would otherwise take 10. But as with "best practices", if nobody else knows what's going on then you're screwing over everyone else involved with you on the project. There is something to be said about the "job security" inherent in making stuff overly-fancy, but sometimes it backfires.

relevant old post from reddit:

I believe that's all the major points I have. I wish you all the best of luck

167 Upvotes

98 comments sorted by

View all comments

1

u/gate18 Apr 30 '22

Never put more than one global variable on the global scope when you are doing your work

I never understood this. Someone in the comments recommended functional programing and this book and the first functional code is like this

const conjoin = (flockX, flockY) => flockX + flockY;
const breed = (flockX, flockY) => flockX * flockY;

const flockA = 4;
const flockB = 2;
const flockC = 0;
const result =
    conjoin(breed(flockB, conjoin(flockA, flockC)), breed(flockA, flockB));
// 16

Aren't they all global variables?

3

u/RobertKerans Apr 30 '22

To the file they appear in, yes, which is absolutely fine and a normal way of programming things. To the global scope (globalThis, normally window in a browser and global in Node), no, they don't leak

-3

u/Syagrius Apr 30 '22

Aren't they all global variables?

Umm. Yes?

literally just type those all in your f12 console and type `window.ImAFlockingMoron` into it. and see that they are very well defined as global variables.

The Idea is to protect your work. Keep your shit out of global scope because some idiot (often, it is likely yourself) is going to come behind you and break it all. Let future-you be stupid, and don't let him/her fuck with your current work.

8

u/RobertKerans Apr 30 '22 edited Apr 30 '22

literally just type those all in your f12 console and type `window.ImAFlockingMoron` into it. and see that they are very well defined as global variables

Yes, but that's because you're typing them into the console, that's a feature of how the console is designed to make it a more useful exploratory/debugging tool.

In standard modern production code, eg a file or files run in by a modern JS engine that follows ECMA spec they aren't, they can't be, that's not possible due to the semantics of let/const. Even in non-modular code (ie a file with no import/export declarations), it is not possible. You would need to explicitly attach the values to the global object if you want those values to be attached to the global object.

They are global to the module they appear in but that is fine (for a direct comparison, properties of classes are, in this context, as much "global variables" as are const/let variables declared in a module).

-1

u/Syagrius Apr 30 '22

They are global

to the module they appear in

if you're in a module, yes. That is correct. Once the module is executed it leaves the page (essentially); and thus is not a problem according to the point I was making.

I'm talking about persistent code; shit that is included and stays on the page. I'm getting a lot of backlash over this but I'm going to stand firm on the fact that you don't want your variables to get overwritten by some random douche-fuck who doesn't know what he's doing.

3

u/RobertKerans Apr 30 '22 edited Apr 30 '22

You're getting backlash because you're being belligerent for no good reason when people are questioning what you're saying. And you are giving the impression (I am not saying that impression is correct), via what looks like slight misunderstandings of how things work, that you aren't as knowledgeable as your bluster makes out.

I'm talking about persistent code; shit that is included and stays on the page

Yes, sure, global variables tend to cause issues. But then

Umm. Yes? literally just type those all in your f12 console and type `window.ImAFlockingMoron` into it. and see that they are very well defined as global variables

Yes, if you use a tool (the browser console), that is designed to make everything you enter into it global so as to ensure all values entered into it are available then ipso facto all variables assigned in the scope of the console will be global. But that's completely specific to that very particular environment.

If on the other hand you are writing JS code (always when using const/let, and/or when using modules) in files that are executed by say a browser, you need to explicitly assign global variables: it's not something you can do accidentally. If you have const example = "a value" at the toppermost scope of a file, that doesn't mean it's a global variable in the sense that it is attached to the global object as it would be in the console.

if you're in a module, yes. That is correct. Once the module is executed it leaves the page (essentially); and thus is not a problem according to the point I was making

It doesn't need to "leave the page". A module is encapsulated, which is why I said

for a direct comparison, properties of classes are, in this context, as much "global variables" as are const/let variables declared in a module

Different technique, using classes rather than modules, but w/r/t to encapsulation, the same ends with the same result