JS Good Practices
I've been learning JS and I am liking it a lot so far. I am using https://www.learn-js.org/ because I like their format and style, but some conventions on the site are outdated and are not the most efficient practice.
Take the most obvious example - the website's use of var
instead of let
or const
. Another example is the use of string concatenation. Because this is an introductory course, the examples primarily show this technique - Ex. console.log("Hello " + variable)
. I've been told using template literals is the best technique and I agree - Ex. console.log(`Hello ${variable}`)
. It's just like f-string formatting
in Python which is just plain awesome! The final practice I have been told is to skip the semicolons at the end of statements because JS uses Automatic Semicolon Insertion.
My question is What are good practices and habits in JS as well as practices to avoid? Feel free to list your favorite techniques and pet peeves in the comments - I'm eager to read them!
Credit to
@MrEconomical and @AtticusKuhn for the 3 listed tips!Two that I can think of off hand.
- Use descriptive variable and function names
- Split the logic of your program into functions. Ideally each one will do just one thing
A little light reading:
- Google style guide: https://google.github.io/styleguide/jsguide.html
- Airbnb style guide: https://github.com/airbnb/javascript
nice to see that you are learning some javascript!
here are a few more good practices to consider:
===
instead of==
- the difference is that==
does a type conversion before checking equality so you get stuff liketrue == []
being true, while===
does not do a type conversion but rather checks strict equalitythis
context inside the lambda is the same as thethis
context outside!innerText
instead ofinnerHTML
-innerHTML
is dangerous as it sets the HTML of an element directly, and any malicious scripts with<script>
could be injected. This is known as an XSS so always useinnerText
to avoid these issuesI hope these tips helped, and good luck on your future JavaScript endeavors!