Bellow, I will explain you some popular JavaScript mistakes
Use const/let instead of var
Replace old fashioned var
with new const
, that will guarantee you better condition of your code.
// bad
var a = ‘foo’
var b = ‘bar’
// good
const a = ‘foo’
const b = ‘bar’
If you really need to change variable use let
, it’s like var
but let
has block range, var has functional range.
What is block variable?
Block variable you can read only in defined block of code where was defined.
for(let i = 0; i < 10; i++) {
let j = 10
console.log(j)
//variable j range
}
console.log(j) //ReferenceError: i is not defined
Functional variable you can read inside whole function not only in the code block.
for(let i = 0; i < 10; i++) {
var j = 10
console.log(j) // 10
}
console.log(j) //10
Both let
and const
are in block range.
Use Template Literals
Manually joining string with +
it’s terrible, it’s bad for refactoring and code readability. The best way for joining words is Template Literals.
If you earlier joined words like that, read this chapter.
const name = ‘Maciej’
console.log(‘Hello ‘+ name + ‘, wave’)
Now I’ll compare the old method with Template Literals.
const name = ‘Maciej’
console.log(`Hello ${name}, wave`)
It’s more clear, right?
In Template Literals you can easily add new lines with only just enter button.
const name = ‘Maciej’
console.log(`Hello ${name}
,wave`)
Copy array with spread operator
I think every one of us sometimes must copy the array, but only half of us know about spread operator.
const array = [1,2,3,4,5]
//bad
const newArray = []
for(let i = 0; i < array.length; i++){
newArray[i] = array[i]
}
//good
const newArray = [...array]
Conditional operators
Every one of us sometimes must or want to use conditional operators from some reasons, sometimes you want to save a couple of lines or make the code cleaner.
const a = 0
let b = 0
!a ? b = 1 : b = 2
Like you see on the above snippet, this is not perfect code it's looks weird.
Below you will see easier way.
b = !a ? 1 : 2
Tadam! Looks better, right?
Thanks for reading 🙏
Changelog:
07/22/2020
Added:
Use const/let instead of var
Use Template Literals
Copy array with spread operator
Conditional operator
If you like this article, please follow me on Twitter @MaciejDEV
Photo by NeONBRAND on Unsplash
Top comments (4)
Nice thank you
You have also :
Regards
Thank you for your attention!
I once intentionally used a var declaration at a C style for loop so the value would be accessible from the outside and I got a React warning asking me not to do it. I went quickly from "I'm a genius!" to "Ima refactor dis..." ):