r/learnjavascript • • 3d ago

Javascript is interesting but is also driving me nuts, how do you actually adapt to writing code without mistakes quickly?

I have been accustomed to C# and Python and have only recently been introduced to one of our projects where we use JS (express and react). I can write good code that eventually happens to work, but I keep falling for really unexpected pitfalls. I realized that most of my mistakes were calling undeclared variables, they are mostly errors that can almost never happen in python or C# because the compiler would immediately point to that piece of code and will usually prevent the app from running. That honestly took a good amount of time and a lot of energy. I understand that it's a regular part of learning, though I want to speed it up.

I know that the browser can ignore these issues so the app ends up running without realizing a problem. Also, that debugging part where console.log() is the best tool in our hand is a headache, it helps but I feel that being able to set breakpoints and move through the whole piece where a bug hides is more efficient.

Don't get me wrong, I am not hating on JS, I love it and I acknowledge that each programming language holds its advantages over other languages. I have in fact spent a good amount of time and put a lot of effort into understanding how to handle JS and react (not a lot but to an extent where I understand its rules and syntax, and can build with it). That's why I want to see how others who may have adapted to JS avoid making these rookie mistakes over and over.

Do not mention asking AI to fix issues or write code instead. I prefer to write code myself.

9 Upvotes

57 comments sorted by

4

u/GiggleSamurai 3d ago

Without migrating to TypeScript, put `"checkJs": true` in a jsconfig.json and VS Code will underline undeclared variables as you type; ESLint's `no-undef` rule catches the same thing. For breakpoints on the Express side, start it with `node --inspect` and attach VS Code or Chrome DevTools, and use the browser's Sources tab for the React side.

4

u/WishGranted11 3d ago

Thanks, this is very helpful!

2

u/realmauer01 3d ago edited 3d ago

Typescript

the first step in programming javascript is naming your files ts instead of js.

1

u/WishGranted11 3d ago

I know typescript can solve these mistakes but the projects we work on are already written in .js and it would unconventional to use .ts instead

1

u/TheRNGuy 1d ago

JSDoc. 

11

u/Beginning-Seat5221 3d ago edited 3d ago

Use TypeScript. Designed by the same guy who designed C#. Serious devs don't really use plain JavaScript.

If you're dealing with a legacy project you can add TypeScript in loose mode - it just sets everything that isn't typed to a wildcard type that isn't checked, but lets you add types incrementally, which you can do with any bit of code that is trouble.

Debugging JavaScript with breakpoints exists - although I don't use it personally.

0

u/azhder 3d ago

That's some BS. Serious people don't use plain JS... right. Way to diss on people. If someone doesn't do it the way you are, they aren't serious.

If you want non-serious, look for people who use TypeScript "in loose mode". That way you get the worst from both worlds: the non-static-type thing you don't like in JS with the overhead of TS which is there just so you can say you use TS, not catching the errors, because "loose mode".

Ha, I just got it, it's a loose-lose scenario.

If I'm paying for the overhead of TS, I will at least get some good use out of it and have it on the strictest of regimes.

Oh, serious people write tests. Tests work regardless if JS or TS or C#...

3

u/realmauer01 3d ago

There is absolutely 0 reason to write in plain javascript nowadays. If you care about the negligible overhead you should go to c or assembly.

Typescript assumes unknown for untyped variables, unknown still gets checked and once it has a shape its not unknown anymore. So just by saving your files as ts files instead of js files you already have an advantage to just plain js. Without even having written one thing in typescript.

0

u/azhder 3d ago

Don't be an absolutist. It is not negligible overhead for some. Once I ended up converting a TS project into a JS project because the person who was supposed to continue maintaining the software couldn't do all that type algebra in their head.

2

u/realmauer01 3d ago edited 3d ago

your converting was stripping types from the files that with a few setting changes weren't needed to setup anymore and renaming the files from ts back to js.

you dont need to have any of that type algebra if you dont care about that.

```ts
const a = {a:"a"}
console.log(a.a)
//here a.a is known, without any written types but only if you save the file as typescript
```

saving the file as typescript makes your ide 10 times smarter

-1

u/azhder 3d ago

No, you can't tell me what I need. Just like I can't tell you what you need. I didn't need anything. Which part of the person not being able to deal with the type algebra in their head is difficult to get?

I show them JavaScript, they can deal with that. I show them TypeScript and they block. They write code that doesn't compile. Time is wasted, code is not working. It's not that hard to understand we aren't talking about what my needs are.

OK, time to stop this thread. Bye

0

u/realmauer01 3d ago edited 3d ago

if the code doesnt compile when there are no types written by the programmer then the code that is running either does nothing cause it hits undefined or throws type errors in production how is that helpful?
there is no type algebra unless you want to use it.

1

u/fabse2308 3d ago

Why would you write in plain JavaScript nowadays?

-2

u/Beginning-Seat5221 3d ago edited 3d ago

TS in loose mode is actually pretty good. It's effectively zero overhead, just gotta rename to .ts and then use type stripping in node. Then you can take any piece of code in the project and add types when you want.

Don't get me wrong, I don't use loose mode, I even use a fork of TS with stricter types, but if you have a JS project and you're new to TS, trying to convert that is hell on earth. That's where loose is useful to let a person start using types with no starting cost.

Tests are great too, no doubt, but type checking is cheaper, so it's a great first line of defence.

4

u/azhder 3d ago

Why do people think “overhead” is some lost CPU cycles? It’s mostly mental overhead.

It’s like not recognizing there are two parts on a seesaw: one that goes down and one that goes up. For every “it solves a class of problems” you hear, ask them (or yourself) what class of new problems you are getting.

A good static type language should not outsource its compiler work onto human brains. Type algebra is a mental overhead.

At this point, I’d be OK if people just read one thread before making the same comment and re-threading the same talking points.

Bye

-1

u/Beginning-Seat5221 3d ago

Stock JS with no changes compiles under loose TS. Not sure why your brain struggles with having to do nothing. Must be tough for you.

1

u/delventhalz 2d ago

  Serious devs don't really use plain JavaScript.

While I lean towards using TypeScript on large team projects, this statement is plainly not true.

2

u/TheRNGuy 1d ago edited 1d ago

I'd use TypeScript as a solo dev tool. 

Why you can't do that? There's no reason to make your work harder. 

Maybe not rookie, but more correct word would be stubborn.

1

u/delventhalz 1d ago

TypeScript does not offer enough utility to me on smaller projects for it to be an automatic choice. I don’t what about weighing the costs vs benefits makes me stubborn, but certainly you are free to inflexibly advocate for your favorite tools on your projects.

1

u/TheRNGuy 1d ago

It's about easier to debug, not about utility. 

1

u/delventhalz 1d ago

How does being easier to debug not add utility?

1

u/Beginning-Seat5221 2d ago

It's OK to be a rookie.

1

u/delventhalz 2d ago

Sure is. You are arguing that the developers of react, webpack, d3, etc are rookies compared to you because you prefer TypeScript?

1

u/Beginning-Seat5221 2d ago

React is written in Flow, which is TS equivalent.

Webpack is from earlier times, see what rollup is written in.

Haven't heard of d3. Their main repo doesn't seem to contain their source.

2

u/delventhalz 2d ago

Ah, well, if you've never heard of the largest JavaScript data visualization library then they must be the ones who are the rookies!

Look, I'm not going to play no true Scotsman with JavaScript libraries with you. Different teams choose different tools for different reasons. Some choose JavaScript. Some choose TypeScript. Some choose TypeScript but then change their minds and switch back to JavaScript. None of this is indicative of being a rookie or unserious.

What smells desperately rookie to me is trying to use unthinking loyalty to some arbitrary tool as a badge of superiority. You've got what, 3-5 years of experience? Just got the word "senior" added to your job title and are all eager to prove to the strangers on reddit how clever you are?

1

u/Beginning-Seat5221 2d ago

About 20 years experience. Never really done much data visualization though.

The world is made up of all types, I guess some "serious" devs might choose to use JS, but I don't see any reason to, except for the main one, which is devs who don't know TS. When my TS skills were weaker I might have chosen JS, but once familiar with TS the cost is very low and the benefit very high.

2

u/delventhalz 2d ago

If that’s the case, you certainly don’t come off that way.

Plenty of ink has already been spilled about why a team might choose JavaScript over TypeScript. If you can’t conceive of any reason other than, “they must just not get TypeScript”, then that reflects more on your lack of imagination and engagement with the dev community than anything else.

1

u/Beginning-Seat5221 2d ago

What advantages have been put forward for using JavaScript?

I know there was some talk of Svelte moving away from TS to using JSDocs - but I think they were still type checking and I'm not sure what else what doing to type checking but typescript.

Other than that?

As I said earlier, you can use typescript in loose mode, where plain JavaScript will compile, if you really want to, and you can run your .ts files directly in any runtime, so it's really hard to see what advantage pure JS can have.

1

u/delventhalz 2d ago

Honestly, if you are using TypeScript in loose mode, I question why you are bothering with it at all. TS is awesome when it can offer you rock-solid guarantees. When you leave gaps in those guarantees you are adding whole build step for what... better autocomplete? Doesn't seem worth it to me.

Anyway, yes the Svelte team and Turbo 8 team have both famously written about their transition away from TypeScript recently. If you want the details, I recommend you look up what they've written themselves. As you might expect, the reasons mostly boil down to complexity, both in terms of adding to the build process and adding to the mental load of developers. I probably wouldn't have made the same decision myself for Svelte or Turbo 8. For projects and teams of that size and complexity, I think the trade offs are worth it. But as the teams and projects gets smaller, I am more and more sympathetic to just keeping things simple.

Tools have to carry their weight to convince me to deal with them. TypeScript often does, but if I'm just throwing together a portfolio page or a small web app or something, no I'm not bothering.

→ More replies

1

u/TheRNGuy 1d ago

No, because you prefer JS. 

1

u/delventhalz 1d ago

The developers of react, webpack, d3, etc are rookies because I prefer JS? What a weird thing to say.

1

u/azhder 3d ago

I run the code while I'm writing it. That's how you end up writing code without mistakes quickly. You have a quick feedback.

And guess what, they are errors that almost never happen to me, just you. Why? Because I'm used to the language. So, it's not the language, it's you. You just lack practice... and get some linter and formatter to also run while you type the code.

Oh, and don't' forget writing tests.

4

u/WishGranted11 3d ago

I installed eslint to prevent those pitfalls, and have also installed prettier to format my code.
Unfortunately, I haven't been writing tests, though I was always testing it myself.

I know about unit testing conceptually but I haven't implemented anything related to it yet. I haven't seen anyone doing it in the company I work for, I do not know if it depends on what software we create or is about the engineers doing the work. I honestly cannot tell when I truly need unit testing in my code.
Can you please tell me a bit about it based on your expertise and perhaps guide me to some articles/documentations related to unit testing that you found helpful and thorough?

2

u/azhder 3d ago

Almost no one will give you the time to write tests. You will have to allocate the tome for it without letting others know.

If you write pure functions (like in functional programming style), your test can be simple array of [result, arg1, arg2] tuples that check your functions.

There are a few style changes that help, but I doubt others on your project are using and will even be open to using. People should not write one language in a way they write another. If your code in JS and TS and C# looks the same, you’re probably using it wrong in at least one, maybe even all.

I mean, how can you explain to someone that a more robust code would mostly have functions that take a single argument and return one? People used to writing C# functions with 6 to 10 arguments will find it weird.

2

u/wagaiznogoud 3d ago

The errors you’re describing should be easily debuggable from reading the logs. There’s also breakpoints you can set with the chrome devtools

2

u/DinTaiFung 3d ago edited 3d ago

You need to set up a linter in your JavaScript/TypeScript IDE.

When your IDE has been set up with live linting, while writing code the IDE will provide immediate feedback when you create code that may be cruft, something that is prone to failure, bad practice, or a blatant syntax error.

A Simple Example

JavaScript/TypeScript file:

// initialize counts object
const counts = { external: 0, internal: 0 }

If the scope you're in never uses the variable counts, then the linter will show a warning color underlining the counts variable in your editor's buffer.

This indicator should be conspicuous enough that you notice it.

And if you mouse over it, you will see a message:

'counts' is assigned a value but never used.

In this example, the variable initialization is perfectly legal and will not throw any run-time errors. However, the linter detects that this is unused code (cruft) and should be addressed.

In general, the linter will do two things:

  1. Alert you to mistakes as you write code.

  2. Teach you common pitfalls and how to avoid them.

Properly setting up a linter in your editor is sometimes not simple and straightforward. But after spending the effort to do this, your coding quality of life will immeasurably improve.

Have fun and best of luck!

P.S. I use Zed editor and oxlint. There are other freely available choices that achieve the same goals. Use whatever suits you best.

2

u/HipHopHuman 3d ago

Everyone telling you to use TypeScript is mostly correct - if you are a C# enjoyer, TypeScript will feel very similar. Both languages were designed by the same guy. That being said, there are a lot of weird differences between TS and C# that will throw you off and only time & practice can fix that. There's also a huge footgun with TS: The type-system syntax is turing-complete, so there's no end to how complex you can make it. When writing TS, you have to be constantly aware of when you're overdoing it. So, one of the TS best practices is to "rely on type inference as much as possible".

For surface-level issues, sometimes you can get by with just using a linter. It can catch undeclared variables, unused variables, and a few other antipatterns all on its own without involving TypeScript.

Also, don't treat JavaScript as the glorious programming language it presents itself as - instead, treat it like your favourite drunk uncle, because it's basically the programming language equivalent. The mindset shift helps, as weird as it sounds. Your favorite drunk uncle is mostly relaxed and very flexible, with a lot of great stories to tell - but sometimes you just have to let him lean on your shoulder and baby him a little so he doesn't fall flat face-first into concrete.

As for debugging with breakpoints, that is possible in all the major browser devtools. Google Chrome's devtools experience is basically the industry standard, so you'll want to heavily scour the documentation and learn everything in there. There are ways to connect these devtools to server-side JS as well. This gives you a lot more than breakpoints, btw - you have live expressions, network condition simulation, performance monitoring tools and a whole lot more. It's a beast, with a lot of mechanical parts, so don't expect to become an expert at it over a weekend.

1

u/chikamakaleyley helpful 3d ago

your IDE should be equipped with the tooling to catch these things and give you diagnostic display in real time, so a lot of those silly issues are knocked out when you run your code

The LSP for JS is actually the typescript LSP, and it will cover all of js, jsx, ts, tsx file formats

eslint is a simple install, and will call out problematic code

prettier, for formatting, can be setup to apply on save

VSCode, will come with the support out of the box, and if not active is just a checkbox in settings

Neovim just requires a little setup, but easy also

2

u/chikamakaleyley helpful 3d ago

sorry reading this back, TLDR, the tools are available, the setup is easy

1

u/WishGranted11 3d ago

Thanks, I just installed eslint, it is a simple and quick solution to avoid having undeclared variables/functions called, I love it!

1

u/chikamakaleyley helpful 3d ago

its pretty standard to minimally have eslint + prettier in all FE related projects.

Something like... Airbnb, their eslint/prettier config, which you can download, was the one that a lot of companies used as default.

Now if you want to improve development by taking advantage of the features your IDE provides for you, setup the LSP

0

u/markus_obsidian 3d ago

People are going to tell you typescript. And they're not wrong.

The real answer is just practice & discipline. Use tools like jsdoc to properly document your types & behaviors. Use ides & lsps to present you with diagnostic info & informal guards. Remember your mistakes & traps you fall into & codify guards to avoid them.

1

u/WishGranted11 3d ago

I appreciate the advice.
I just installed ESlint into my VS Code and it is too helpful.
I like to document types, functions job, and what functions return with:

/**
 * @param
 * @returns 
 */

It makes diagnosis easier

1

u/azhder 3d ago

JSDoc was made to look like JavaDoc.

The problem is that it’s a language for generating documentation. In Java, types are statically defined, so the JavaDoc doesn’t have to worry about it.

JSDoc was made in the likeness of a language not meant to define static types. It has shortcomings.

1

u/markus_obsidian 3d ago

It does. Doc generation is more or less irrelevant in this day & age with AI. Nevertheless the lsp & ide support is significant. Despite its ugliness & verbosity, I'll still reach for it if typescript is out of reach.

1

u/azhder 3d ago

The better advice would be to add separate .d.ts files

1

u/markus_obsidian 3d ago

A reasonable alternative. Doesn't help devving withing a js module. But type defs between modules is nice. Or a middle ground of defining complex types in d.ts and referencing them in minimal jsdoc.

1

u/GodOfSunHimself 3d ago

Undeclared variables? Use a proper IDE and tools like ESLint. Also switch to TypeScript if possible.

1

u/TheZintis 3d ago

For the C# dev in you Typescript is probably the closest.

Although I do think that you can get a lot of work done with certain code structure/patterns and naming variables well. I feel like after a point I learned a handful of ways to write code and that things kind of cleared up after that. So maybe partially an experience thing (although I don't know how much experience you have).

Also bugs are inevitable.

1

u/Aggressive_Ad_5454 3d ago

Use a good IDE. webstorm is my preference, but VSCode is also just fine. It’ll catch a lot of mistakes for you and help you get your code right.

Every minute you spend learning to use the debugger in your browser devtools will pay back days over your career.

Npm is your friend. Don’t waste time reinventing flat tires.

1

u/TehFocus 3d ago

Writing code without mistakes lol. Wishful thinking. Even our 30 year veteran of a senior regularly makes mistakes

1

u/delventhalz 2d ago

The big thing with JavaScript is it is backwards compatible. That’s pretty much a hard requirement from browser vendors. So while modern JS syntax is mostly pretty well designed, you are going to occasionally run into old cruft that is best avoided.

For example, it sounds kind of like you are using var. Are you using var? You should not be using var. You should be using the modern let and const. The old variable declaration had a strange hoisting behavior where it could be referenced before you declared it, but would have an undefined value. With the newer syntax, that sort of thing blessedly throws an Error. 

The first thing I would do is download eslint and install an opinionated config like AirBnB’s. A linter will do a lot to help you avoid pitfalls, and generally the more opinionated the better. I don’t agree with everything rule AirBnB enforces, but that’s not really the point. An opinionated linter will keep you writing consistent code, with modern syntax, and with a minimum of pitfalls. If you are an experienced solo dev you don’t necessarily need a linter, but it’s a must have for any JS team and should help you as well.

The next thing to think about is TypeScript. This is a language which is a superset of JavaScript, compiles down to JavaScript, and mostly just adds static type checking. It’s made by C# folks so a lot of it may feel familiar. The type checking is extensive, so it can allow tools like VS Code and eslint to surface more sophisticated errors during development. It’s another must have (or nearly so) for JS teams. For solo devs I’m a little more agnostic. Both the compile step and managing the static types adds a fair bit of friction to development. I think that’s usually worth it when you need to keep a team in line. Maybe not for your small/solo projects though. 

1

u/TheRNGuy 1d ago

Know how to debug. 

1

u/TheRNGuy 14h ago

Try unit tests.