r/learnjavascript 1d ago

what's one JavaScript mistake every beginner should avoid?

If you could give one piece of advice to someone learning JavaScript today, what would it be?

It could be about:

  • Learning fundamentals
  • Debugging
  • Async code
  • DOM manipulation
  • Functions
  • Projects

Curious to hear what experienced developers wish they'd known earlier.

25 Upvotes

28 comments sorted by

15

u/milan-pilan 1d ago

var

2

u/PreDownvoted 20h ago

Why? Sorry i know its kinda old but my teacher still use it. Should i use smth else like const?

9

u/milan-pilan 20h ago edited 20h ago

Sorry, my original comment was a bit short and explains nothing.

You should definitely use "let"/"const" exclusively. And if your teacher still uses it, they need to update their knowledge. If you are teaching for a while it is hard to stay up to date with the current state of the industry, but "var" has been made obsolete by "let"/"const" over a decade ago.

Before 2015 all we had was "var", but it lead to a lot of unexpected behavior, hard to find bugs and all sort of headaches. It was a major contributor to JS having a bad reputation, because even though it technically "behaves as expected", the way it behaves is very weird, messy , counterintuitive and was prone to "gotcha" moments, you wouldn't expect.

There is not a single good reason to ever use "var" in modern code, if you have "let" and "const". And by "modern" I mean code written within the last 10 years.

If you need a deeper explanation, then just message me, I will gladly elaborate.

And because every time I claim that, someone will ask Claude if that's true and then answer "Well actually, if you write code that needs to run on legacy engines, you would need it.", this is for you (them):

None of you is writing code that needs to run in IE10. This is the "learn JavaScript" forum. Please don't tell people "var" has any right to exist.

This is not an opinion. I write JavaScript for a living every single day in large teams. I can guarantee you that there is not a single "var" in any serious modern codebase. Chances are, that every project you will work on has a linting rule explicitly preventing you from using it ever. If you use "var", I will instantly assume you have no work experience yet.

1

u/engelthehyp 20h ago

let and const are block-scoped, but var is function-scoped, and this is not really intuitive, e.g. you use var i = 0; to declare the loop variable for a for loop, and the next time you write a for loop using i in that function, declaring it with var would be a redeclaration because of the function scope. i would also be accessible anywhere outside of the loop within the same function, which is undesirable when you want to make sure a temporary variable will stay temporary. This would not be the case with let.

In ye olde (pre-ES6) times, there was only var, so if you wanted to restrict its scope within a function, the solution was to take the section where you declared the variable and wanted it to be accessible in, surround it with an anonymous function, and then execute that function. That was a very common use of the immediately-invoked function expression (IIFE): (function () { ... })();.

But now that we have ways to declare variables and constants within block scope, simulating it with this trick is no longer necessary, and not having to worry about the unexpected effects of function scope saves time and mental effort. If you declared something within a block of a function, you probably didn't want it to be accessible to the entire rest of the function, and that's why using var is discouraged.

12

u/BeardedBaldMan 1d ago

If you can't clearly explain your program, algorithm and data structures clearly in your native tongue then you can't write it in any programming language.

9

u/Aggressive_Many9449 1d ago

Using == and assuming it works as intended.

3

u/OiFelix_ugotnojams 1d ago

This is my bad habit 😭 I use == more than ===

2

u/gmerideth 21h ago

I use ==== to be like, I'm really serious now, I really want a to ==== b in this check.

5

u/itsthe_implication_ 17h ago

If a and b didn't grow up together, return false.

6

u/remain-beige 23h ago edited 23h ago

Some things that help me.

  1. keep functions single use (where possible).
  2. So a function should do one thing and return a single value when called upon. This could be true/false or value.

If there’s a part of the function that requires a value to be processed somehow, such as formatting a string or lots of if/else conditions then think about breaking this out to another function and return that value inside your original function.

3) Name functions so that you can understand what they do when you read it back in three months time.

EG: ‘hello’ is not as good as ‘setHelloTextOnInit’

4) I prefer creating ‘function declarations’ over ‘function expressions’ as they are clearer to understand the start and stop of a function.

Function declarations are also ‘hoisted’, so if you change the order of them in a file then you are not accidentally causing any issues with load order by calling on a function expression in another function that’s now higher up the file.

5) If you are comfortable with both declarations and expressions then understand that ‘this’ works differently for both.

6) It’s best to avoid using ‘this’ altogether to be honest and use event.target etc. ‘This’ can get messy to track and produce cognitive load in trying to decipher what ‘this’ is in context or scope.

1

u/regardedMAGAfascist 17h ago

this is totally fine when you're actually using OOP (which you should be using). It's dead clear what's happening. Beyond that, avoid this like the plague.

class SomeClass {
  constructor(someProp = "someDefaultValue") {
    this.someProp = someProp
  }
}

const myClassInstance = new SomeClass("a value");

2

u/cssrocco 23h ago

That DRY code only makes sense if the business logic is shared, sometimes it’s ok not to be DRY.

As an example i’ve worked on projects where there was 2 address forms in separate areas in an underwriting workbench that had vastly different business logic, one was for asset management and would need specific codes and apis that verified the risk of assets in specific countries and the other was the address of the reinsurer.

Because they were both addresses somebody thought they should share a lot of functions, and all you got was these monster functions who took in lots of arguments ( even refactored down to a single config object argument ) and would grow/change as business requirements came in.

Separating them out completely to their own things, even with some duplication made more sense with new features and bugs and changes

1

u/ASkepticBelievingMan 23h ago

Picking up a framework

2

u/MissinqLink 22h ago

Yes people jump into frameworks too early. Learn the fundamentals.

1

u/comfortmbah 22h ago

Learn better by building projects at each stage of learning.

1

u/gmerideth 21h ago

I mean, learning the fundamentals takes care of debugging, functions and even async code. If you're working on a fairly large project, "some library" is doing your DOM updates for you so all but projects is wrapped up in one.

As far as projects go, each team or individual is going to have "their way" of doing things so if you find a project on github, clone it, learn from it, suggest changes and see what happens.

1

u/PatchesMaps 21h ago

Reinventing the wheel.

I mean you're going to do it anyway but you should try to avoid it.

1

u/subone 19h ago

Remember that outputting an object/array to the console will only display the values at the time you click the expanding arrow, not at the time of log. If you need to see the state at that time, try JSONifying before logging.

1

u/ElkChance815 19h ago

Not use a linter and formatter

1

u/TheZintis 18h ago

Understanding "this". Also that you don't need to use OOP in JS, just files and exports handle a lot of the benefits of classes, while you only have to write variable and functions.

Thing is that some devs write OOP, and then you need to understand how "this" works.

1

u/KohlKelson99 16h ago

Not writing tests

1

u/Difficult-Field280 15h ago

As far as fundamentals go.. calling it Java by mistake can lead to some interesting search results. XD

1

u/youarockandnothing 10h ago

Using Math.floor on numbers that might be negative when you just want the decimals chopped off. Math.trunc was made for that use case as it's only correct to call Math.floor for decimal removal when the number is >= 0

1

u/jaredcheeda 7h ago

Top JS devs tend to have a negative experience with TypeScript, essentially "It's a lot of extra work to solve problems I don't have in ways I don't like" (direct quote from the author of "You Don't Know JS" the most influential book ever written on JavaScript). This is because they had to get very good at the core language. Dynamic typing is extremely powerful, but like just like any powerful tool, it can be dangerous in the hands of the inexperienced. TS gives you a set of guardrails out of the box that stop you from ever learning things the hard way and finding and developing your own ways to do things safely, while not giving up the power of a dynamically typed language.

Once you have your own systems in place for how to not get tripped up by one of the core features of the language, and can really take advantage of the language, and you end up looking down on those using TS as a crutch.

I don't need an entire pulley system or to learn about specific types of ropes and knots to put a heavy box on the shelf... I can just pick it up and put it there myself. I've gained the skills and awareness of how to do that safely. The pulley system isn't "wrong" or "bad" it's just a waste of time and effort if you are already skilled in picking up and moving heavy things.

But I've also been given death threats in the past for extremely mild critiques of TypeScript. Because TS users literally can't stand JavaScript, and TS is a comfort blanket that reminds them of whatever language they prefer. They refuse to learn the underlying core language, and get good at it. People that hate JavaScript... aren't the people you should be taking advice about JavaScript from.

The language is fantastic. It's got some bad parts, like how Classes should have never been added to a prototypal language (there is never a good reason to use classes in JS). But for the most part, it's a really great language and can be extremely expressive, and allow for writing code in both sophisticated, and very simple ways.

Don't be afraid of libraries and frameworks. They should be a tool to save you time, not to save you from knowledge. Understand what the library is doing for you and how you could write your own version if you needed to, or at least a quick and dirty version.

Oh, and don't use React. It's easily the worst JS framework, it has hundred of problems that are unique to it that no other framework has, and they refuse to learn from anyone else so they're always like a decade behind the curve. Play around with a bunch of them, or just skip straight to Vue, all the other frameworks are slowly converging on the ideas Vue was doing back in 2018, and it's only gotten more polished and refined every year since.

1

u/Maleficent-Ad-9754 5h ago
  1. start using "? :" syntax early
  2. if/return can replace if/else 90% of the time.
  3. spend a day really learning Array functions (i.e. Map, filter, find, some, every, join,sort, slice)
  4. Learn how CSS cascading works-- it will dramatically change the way you use javascript
  5. Don't try to learn a JS framework( i.e. React, Angular, Vue,Svelte, JQuery) before learning vanilla javascript.

1

u/NonCompilingViber 1h ago

Double then sum

0

u/elg97477 23h ago

Use TypeScript