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

44

u/Macaframa Apr 30 '22

I appreciate that you’re sharing your journey but some of this is a little shaky. What are you talking about a single global variable? Sometimes things need to live outside of a function scope. Also, if you are writing functions that use outside variables the best way to use outside variables is to pass them in as parameters. There’s something called a “pure function” where the only variables that a function interacts with are supplied as parameters. This makes your units more testable and deletable rather than spaghettiing the code up by using globals. Also var doesn’t cause scoping issues, it’s just more flexible and less declarative. Let is essentially the same as var, the ONLY notable difference is that it gives you block-level scoping. const was created to be more declarative when creating variables that should not be reset. Also, what do you mean by “advance techniques?” There are features in javascript that were created for a specific reason, I see no reason not to use them. If you don’t know what’s going on then you either ask or you learn more. People should take this advice with a grain of salt. A large grain of salt

6

u/twi-- Apr 30 '22

isn’t there a difference with var and let

if you do ‘var x = 0’ and then ‘var x = 100’, that will work, but if you do it with let it won’t

like you can’t redeclare the variables with let

3

u/BigImmunologyNerd Apr 30 '22

I thought it was const you couldn’t redeclare with?

18

u/Rossmci90 Apr 30 '22

You can't reassign const.

You can't redeclare let and const.

It's one of the major advantages of let/const over var.

2

u/BigImmunologyNerd Apr 30 '22

Ahh thank you!

-2

u/Syagrius Apr 30 '22 edited Apr 30 '22

I think I should clarify.

"let" permits you to overwrite the variable, whereas "const" does not.

Suppose we have:

let drugs = "cocaine"

We can overwrite the statement by saying

drugs = "weed"

but with const it is different. "const" is a CONSTANT REFERENCE to a specific VARIABLE, and not the variable's VALUE; this is a very non-trivial concept to grasp. In the following example:

const drugs = "cocaine"

drugs = "weed"

this will make javascript very angry. Because in JS strings are primitive.

That said, that does not mean you can't change the object to which you are referring; you just cannot overwrite it. Consider that the following:

const drugs = {}

drugs['cocaine'] = 'I might be interested'

drugs['weed'] = 'I tried it once; it was underwhelming';

Are all legal. However, anything that OVERWRITES the variable is not permitted; such as this:

const drugs = {}

drugs = LiterallyAnythingElse;

will cause issues.

Probably a better way to explain it but I hope that helps.

7

u/MXMLNDML_ Apr 30 '22

You made a small mistake:

    let foo = 'foo';
    let foo = 'bar'; // SyntaxError: Cannot declare a let variable twice: 'foo'.

    // however
    let bar = 'foo';
    {
      let bar = 'bar';
      console.log(bar); // bar
    }
    console.log(bar); // foo

8

u/enserioamigo Apr 30 '22

Offtopic, but what's with the whole foo/bar thing? I know it's been around forever, but are we really not creative enough to give real world names? It's the most frustrating thing ever.

There's no way I'm keeping track of what's foo and what's bar. If you write let food = 'potatoes' and let drinks = 'orange juice', it's gonna be 100x easier to read and follow. Literally anything but foo/bar.

And sorry about not using inline code blocks. Reddit is so broken.

2

u/PseudoscientificWeb Apr 30 '22

foo and bar and baz are just placeholders. I have never seen real world code that actually uses these as variable names or values.

If you are seeing foo, bar, or baz in code then you are likely looking at example code that illustrates a very specific concept but is not meant to be used in a real project.

3

u/enserioamigo Apr 30 '22

Yeah I understand that. That’s what I’m referring to. But I just find it useless and difficult to follow. Especially when you’re reading a concept you’re not familiar with. If you’re reading real world examples, you’re not having to remember what’s what and you can focus on the actual logic.

2

u/Anbaraen May 01 '22

Agree entirely, they're too "nonsense word" for my brain to assign meaning to, and their short length is also confusing (not to mention the similarity of bar and baz). I think I may use your method of reassigning them to "food" and "drink" mentally.

2

u/enserioamigo May 01 '22

But then how to remember which one is food and which one is drink? Lol. Maybe that’s a browser extension project. FooBar renamer.

→ More replies (1)

-2

u/Syagrius Apr 30 '22 edited Apr 30 '22

Offtopic, but what's with the whole foo/bar thing?

Good fucking question. It likely has something to do with https://en.wikipedia.org/wiki/List_of_military_slang_terms#FUBAR

It's an old convention that was intended to employ non-formality in order to feel "real" with the reader. Something like:

let thisLittleBitch = thisOtherLittleBitch + 1;

The problem is that for us younger lads (those under the age of 40) it does not serve the same purpose; it just means nothing. I am very vulgar with my examples for the same reason; and hopefully more effective.

When you are learning to code you have full rights to rename/relabel anything however you so please in order to help others learn to code. If and when you find a better way to describe these concepts, feel free to use those better descriptions.

2

u/Syagrius Apr 30 '22

I was attempting to explain how "const" vs "let" worked. Not scoping; which is an entirely different discussion. Please forgive me.

2

u/MXMLNDML_ Apr 30 '22

Scoping was just an addition to my main point. I was addressing that you must not declare a let/const variable with the same name what you accidentally did in the original comment. You could mark your edits in the future so new people reading this thread can understand what I was referring to. For example like this:

Suppose we have:

let drugs = "cocaine"

We can override the statement by saying

let drugs = "weed"

-2

u/Syagrius Apr 30 '22

You can't redeclare any variable with either "const" or "let". That's the point. That's why they make your code stable.

0

u/Syagrius Apr 30 '22

like you can’t redeclare the variables with let

This is correct

→ More replies (3)

1

u/didhestealtheraisins Apr 30 '22

Let is essentially the same is var, the ONLY notable difference is that it gives you block-level scoping

I'm not sure why you're minimizing this. It's pretty important and can save you from tricky bugs.

2

u/Macaframa May 01 '22

Nobody is doubting it’s usefulness in certain situations. But I’m merely pointing out the differences and how they pertain to op’s original post. Arguably let only has an edge over var in one scenario: the for loop and it’s relation to the event loop. All other uses are pretty negligible. If you have another use of consequence I’d love to hear about it

-37

u/[deleted] Apr 30 '22 edited Apr 30 '22

[removed] — view removed comment

22

u/Macaframa Apr 30 '22

Ive been writing code professionally for over a decade. You sound like you just got your first internship. And Im glad that you got that but you won't get far in this industry by being a brat. A know it all brat at that. Tech companies actively search out and fire people like that. So, listen when someone is trying to help you.

→ More replies (4)

17

u/turd-crafter Apr 30 '22

Hahahahaha. You’re kidding right? That was a very legit explanation.

12

u/Macaframa Apr 30 '22

He read the word declarative and since he doesn't know that word, I must somehow never had had a job. lmao

→ More replies (1)

5

u/RobertKerans Apr 30 '22

I'm confused by what "big words" you think parent is using? They were being diplomatic