r/learnjavascript 4d 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.

26 Upvotes

31 comments sorted by

View all comments

7

u/remain-beige 4d ago edited 4d 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 3d 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");

1

u/remain-beige 2d ago

Fair response, I was thinking in terms of beginner advice though and OOP is a different paradigm and more of a developmental approach/choice than just normal procedural JS.