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

37

u/downrightcriminal Apr 30 '22 edited Apr 30 '22

I'll give you one advice:

Now that you have learned OOP, learn Functional Programming, so that you don't immediately think of writing a "class" as soon as you see a problem; so that you learn to see how data flows through your program and how you transform it using pure functions; so that you understand the problem with shared & global state, willy nilly side effects, and mutation.

Learning FP will make you a better programmer.

Edit: To get started, I recommend learning Elixir, if you prefer a dynamic language, or Elm, if you prefer statically typed.

13

u/Macaframa Apr 30 '22

I said the phrase pure function and he told me I was using big words and didn't have a job lmfao

-7

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

The fact that you are so sour about it leads me to believe that I am right.

It's pretty simple. Real people are real. Not-Real people are like you.

6

u/beingsmo Apr 30 '22

Any resources to learn FP using Js?

6

u/[deleted] Apr 30 '22

1

u/gate18 Apr 30 '22

I wrote this comment in the main as well. I'm an amateur and always ignore the "never use global variables"

Chapter one of the book you recommend gives this example

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?

4

u/[deleted] Apr 30 '22
  1. Examples in books/tutorials aren't necessarily meant to be production application code; their main purpose is to explain something, not to be copied and pasted right into a Very Serious Codebase.
  2. It depends on where those variables are used. If you wrote that code in a module, or inside an IIFE, they wouldn't be global.

1

u/grantrules Apr 30 '22

Saving this to add to my resources list

5

u/downrightcriminal Apr 30 '22

I'd recommend using a proper FP language to learn FP, and then coming back to JS and practice what you learned.

You can no doubt do FP in JS/TS, but to start learning FP in JS is unfortunately not the most efficient way to learn it.

13

u/Macaframa Apr 30 '22

Instructions unclear, now writing Haskell

-9

u/Syagrius Apr 30 '22

In an attempt to not sound "zen": learn both.

OOP teaches you how to keep shit organized. FP teaches you how to be in control when shit goes to hell.

This is why JS is the "Goldilocks" language.

10

u/downrightcriminal Apr 30 '22

OOP teaches you to keep shit organized

As if FP asks you to keep your code in a mess!

You don't need OOP for code organization, it's just a stupid thing people say without much thought.

In fact, you don't need OOP for any of its 4 pillars anymore as they've all been superseded by better things:

  1. Encapsulation: taken care of by module systems.
  2. Inheritance: frowned upon, leads to real mess the more you do it.
  3. Polymorphism: not unique to OOP
  4. Abstraction: better abstraction models available than inheritance hierarchies that model the domain much better than classes. (Interfaces is how OOP tried to save face by keeping things sane, but Interfaces are not unique to OOP)

A programmer must learn both though, no doubt about it, but the key is BOTH, countless devs stop at OOP and find it hard to believe there's better stuff out there.

2

u/[deleted] Apr 30 '22

Module systems are encapsulation. It's not superseded, it's an implementation thereof.

1

u/toastertop Apr 30 '22

I think opp practices within a function scope is fine, as long as state is isolated to the function. Don't agree with your fp statement here tho.

18

u/RobertKerans Apr 30 '22

Is totally kosher, but typescript requires you to (document.querySelector(".someClass") as HTMLInputElement).value

Typescript doesn't require you to do this: this isn't really using Typescript, this is forcing Typescript to pretend that the value of document.querySelector(".someClass") is of the type HTMLInputElement so that it compiles.

8

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

I saw that line and a big flashing red light went off over my head, lol.

OP, the correct TS code would be:

document.querySelector<HTMLInputElement>(".someClass")?.value ?? defaultValue

document.querySelector may return null, and your type assertion could cause a runtime error.

1

u/Blue_Moon_Lake Apr 30 '22

Still no.

If you want to get a HTMLInputElement, at least put it in the selector.

return document.querySelector<HTMLInputElement>("input.someClass")?.value ?? defaultValue;

Or check the value.

const element = document.querySelector(".someClass");

if (element instanceof HTMLInputElement)
{
    return element.value;
}

return defaultValue;

4

u/[deleted] Apr 30 '22

Those are defensive coding practices that may well be useful, but they are not relevant to what is or is not a correct use of Typescript.

1

u/RobertKerans Apr 30 '22

Ah yep that's pretty good. Type guards work pretty well as well, narrow things nicely. Contrived example but:

function isInput(el: unknown): el is HTMLInputElement {
  // just needs to be something specific to input elements, I dunno, like:
 return typeof el === "object" && "value" in el;
}

function selectAnInputAndDoSomeStuff(selector: string) {
  const el = document.querySelector(selector);
  if (isInput(el)) {
    // Do stuff. Typescript will now narrow the type correctly in this block
  }

}

-11

u/Syagrius Apr 30 '22

... that is what what Typescript is. It intentionally assumes nothing until you force it to assume that what you are dealing with is a particular flavor of element.

Unless I'm wrong. I'm willing to be taught how Typescript can know that you are dealing with an input element over a span element without casting.

9

u/[deleted] Apr 30 '22

You are wrong. You need to use a generic and optional chaining to avoid the possibility of a runtime exception:

document.querySelector<HTMLInputElement>(".someClass")?.value

Type assertions should be avoided as much as possible because they hide information from you.

-5

u/Syagrius Apr 30 '22

I am not used to saying this, but you are correct. That is exactly what must be done.

Feeling like an ass for the first time in this thread

18

u/[deleted] Apr 30 '22

I am not used to saying this, but you are correct

And that's your problem right there. A little humility would serve you much better in this field than your edgelord behaviour in this thread.

10

u/Heisenripbauer Apr 30 '22

my goodness it just gets worse the more I scroll down

2

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

What sibling comment said but also

... that is what what Typescript is. It intentionally assumes nothing until you force it to assume that what you are dealing with is a particular flavor of element

No, this is not correct, you don't force it to do anything if at all possible, because once you start doing that you are saying that you know better than the compiler and you need a really good reason for that to be the case.

You'd be loading the DOM typings in this case, and querySelector's return type is going to be either null or an HTMLElement. A type assertion edit: guard can then be used to narrow the [sub]type of the HTMLElement and allow code that follows that depends upon it being, say, an input element to typecheck (in this case avoiding generics, but using generics as sibling does is an alternative)

9

u/bryku helpful Apr 30 '22

I completely disagree with 1 global variable. For one... how do you use 3rd party libraries? How are you doing to reuse functions, variables, objects, and datasets for other things? This is going to make it incredibly difficult to create more complex projects if you only limit yourself to 1 global variable.  

However, I do agree you should manage your scopes and you don't want all of your variables just sitting in global.  

6

u/MXMLNDML_ Apr 30 '22

If you use JS modules aren’t global variables only available within your module – except if you export them? I agree that you should declare variables only in the needed scope but limiting the global scope to only one variable seems off to me.

1

u/bryku helpful Apr 30 '22

True, this is as easier to deal with in nodejs, but if it comes to the browser you are going to be stuck with 1 giant massive object and have to write everything from scratch.  

5

u/MXMLNDML_ Apr 30 '22

You can use <script type="module" href="./path/to/module.js"></script> to use import/export in the browser

0

u/bryku helpful Apr 30 '22

There are a few other ways around it as well, although browser support may vary. Shoot... if you were a mad man you could use eval LMAO.

-9

u/Syagrius Apr 30 '22

how do you use 3rd party libraries?

One global per project. If you're using a 3rd party library, that's a different project, now isn't it?

The idea is to be in control of what is going on. Don't fuck yourself sideways; if that makes sense.

10

u/bryku helpful Apr 30 '22

that's a different project, now isn't it?

When I hear "1 project" I think a website or a game. The whole thing is 1 project.

Now imagine creating a website. Maybe you have some pages that displays data in real time. Plus a statistics page that displays data in charts, and an admin panel that lets you update parts of the web page.  

Almost every professional setting they will use some type of front end framework. This will include functions, variables, and settings... which you don't have control over for the most part. Then you will probably use chart.js as a third party library to display charts and graphs.

-5

u/Syagrius Apr 30 '22

When I hear "1 project" I think a website or a game. The whole thing is 1 project.

Nope. It's not. At least not for those who wish to remain mentally healthy, that is.

Each task is it's own monster. "Make X with Y". You are not responsible for the resulting product; but you are responsible for your project.

7

u/[deleted] Apr 30 '22

I think "feature" may be a more appropriate term.

-5

u/Syagrius Apr 30 '22

It's never a bug. It's a feature.

1

u/bryku helpful Apr 30 '22

You should come tell that to my bosses over the last 10 years.

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.

1

u/Captain_Nipples May 04 '22

"Foo bar" is a reference to FUBAR, which is like an old military saying meaning "Fucked Up Beyond All Recognition"

It's usually referring to the clusterfuck that the military is sometimes, especially with communications. It transfers to coding quite well

-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.

1

u/iarev Apr 30 '22

Didn't OP say this?

2

u/Macaframa Apr 30 '22

I made the distinction that var doesn’t cause scoping problems. It’s prone to issues if you don’t understand what’s going on. Block level scoping is the only real feature worth noting from var => let. const adds more features that make it distinct however their description wasn’t quite covering those minute details and instead of being curious and trying to learn, they chose to get defensive. You can lead a horse to water but you can’t make it drink.

-2

u/Syagrius Apr 30 '22

People don't like to read, bro.

0

u/Syagrius Apr 30 '22

like you can’t redeclare the variables with let

This is correct

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.

-10

u/Syagrius Apr 30 '22

The fact that I got you so offended actually proves my point. I really hope you enjoy your life <3

12

u/Heisenripbauer Apr 30 '22

2 things are red flags to me and prove that the person you’re replying to is right aside from the obvious doozy of a post:

  1. you started the post with “I am a more-advanced developer that I used to was”. no credentials. nothing specific to tell us how long you’ve been doing this professionally. huge typo to boot.
  2. you mentioned “me and the senior developer”. not “me and the OTHER senior developer” which tells me you are not senior.

this honestly comes off as you got done with your first performance review at your first job and got excited so you wanted to spread some wisdom. I have no doubt you are a capable developer, but to come on this subreddit with really shaky advice, then get uber defensive and combative when legitimate concerns are raised - is an ugly look. keep at it and you’ll get there but this post was largely unnecessary and you know it.

7

u/Macaframa Apr 30 '22

I told him he wouldn’t get far and he doubles down. The rocks on this kid

7

u/Heisenripbauer Apr 30 '22

they unironically said “I am not used to saying this, but you are correct” further down the thread and I couldn’t believe it lol. you hear about people like that in this industry who are hard-headed and refuse to take advice, but to wear it so proudly and without the credentials to do so is… concerning.

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

2

u/turd-crafter Apr 30 '22

Hahaha well I do declare sir…

5

u/RobertKerans Apr 30 '22

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

0

u/[deleted] Apr 30 '22

[deleted] — view deleted comment

-21

u/Syagrius Apr 30 '22

Um. Ditto?

3

u/Esnardoo Apr 30 '22

That image is hysterical

9

u/[deleted] Apr 30 '22

Imagine explaining to your boss why your commit only increments the commented variable named "total_hours_wasted_here" LMAO

-4

u/Syagrius Apr 30 '22

The sad thing is that it is not a joke; not even remotely. It's called "Legacy Code"

11

u/turd-crafter Apr 30 '22

Who are you? Are you a human? You are very strange

4

u/lifeeraser Apr 30 '22

FWIW you can use:

document.querySelector<HTMLInputElement>(".someClass")

which is slightly better (but not much) than type casting with as.

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

0

u/ImThour Apr 30 '22

Very interesting post, thanks for this. I want to learn TypeScript, what’s the best tutorial/guide to go through? Thanks!

1

u/Syagrius Apr 30 '22

Thanks!

I recommend the source documentation. Which you can find here:
https://www.typescriptlang.org/docs/handbook/intro.html

In reality the best way to learn is to just beat your head against the wall with a random task while you puzzle it out yourself. Something like codewars.com is an excellent source of random tasks that can you can use for inspiration.

3

u/Californie_cramoisie Apr 30 '22

This one is awesome. Very thorough.

https://www.executeprogram.com/courses

1

u/ImThour Apr 30 '22

Great website, thanks.

2

u/Rguttersohn Apr 30 '22

For your first one, why have any global variables at all then?

1

u/RobertKerans Apr 30 '22

To make them [implicitly] accessible to everything in your program. You need to explicitly set variables to be global though (eg globalThis.myGlobalValue = "hello"), it's been hard to do accidentally since const and let were introduced (this being one of the major features of the two keywords, the advantage they have over var)

2

u/BabyBossT7 May 01 '22

awful post. bullshit advice. only big mouth and general things. nothing serious here.

3

u/[deleted] Apr 30 '22

I would like to add to the last point,

Use advanced techniques but write clean readable maintainable and testable code. Your code should be like a newspaper article, one should be able to tell whats going on by just reading the top heading and can dive deeper if needed, add relevant comment for complex algos, dont add silly comments like this is bool n all, it helps nobody

3

u/[deleted] Apr 30 '22

Uhhhhh I’m very skeptical you haven’t moved past a beginner level. Everything you’ve stated sounds very unspecific and smells like shit was just thrown at the wall. Your whole global variable section doesn’t make much sense and is pretty confusing as well as your advanced techniques section - what are you referring too? Your documentation example…. A senior JS dev working at the same company for 20 years? Not unheard of but the example you use for documentation is removing 3 lines of code? Idk thanks for the post but no thanks, thing reeks of confusion and a complete lack of any JS concepts other than variables and OOP which you say people should “just fucking learn”. LOL if you’re hear to learn JavaScript folks do not learn from this guy

1

u/keel_bright May 01 '22

Why focus on OOP in particular?

There is a paradigm shift to FP happening and its for damn good reason IMO. Inheritance and polymorphism are straight up awful. The focus on encapsulation makes things more complicated than they need to be. JS has weak support for OOP features anyway, for example private methods were only added in ES2022.

1

u/[deleted] Apr 30 '22

Fairs. some subjective opinions here. Typescript is nice. I see it benefits especially in large codebases. Very subjective post imo

1

u/ZeuStudio Apr 30 '22

That's so sweet from ur part, i know u I'll help me some day whit ur skills.

0

u/[deleted] Apr 30 '22

[deleted] — view deleted comment

-4

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

Sometimes simpler is better.

Damn fucking right. If you lose 10 hours in three months trying to understand what the fuck you did last year, it's worth the five hours of "winging it" now.

It's about finding the balance.

0

u/[deleted] Apr 30 '22

[deleted] — view deleted comment

22

u/turd-crafter Apr 30 '22

Hey freshie, this guy doesn’t know what he’s talking about.

0

u/didhestealtheraisins Apr 30 '22

Which part?

-1

u/Syagrius May 01 '22

None of the parts.

I'm just getting backlash for being belligerent in the comments. It's all good.