As a Front-end Engineer, 10 Useful JavaScript Coding Techniques That You Should Use

Please be sure to learn these skills.

fatfish

--

Preface

In the past, I wrote a lot of junk code, and now that looks terrible.

When I saw those code fragments again, I even doubted whether I was suitable to be a programmer.

So, here are 10 JavaScript tips to help you avoid writing the kind of junk code I once did.

1. Promise callback hell

Promises provide an elegant way to handle asynchronous operations in JavaScript. This is also one of the solutions to avoid “callback hell”. But I didn’t really understand what it meant, so I wrote this code snippet.

I did these things:

  1. Get the basic information of the user first.
  2. Get a brief summary of all articles by user information.
  3. Get article details through articles briefly.
// ❌
getUserInfo()
.then((userInfo) => {
getArticles(userInfo)
.then((articles) => {
Promise.all(articles.map((article) => getArticleDetail(article)))
.then((articleDetails) => {
console.log(articleDetails)
})
})
})

I’m not taking advantage of Promise here at all. We should handle it like the code snippet below:

// ✅
getUserInfo()
.then((getArticles)
.then((articles) => {
return Promise.all(articles.map((article) => getArticleDetail(article)))
})
.then((articleDetails) => {
console.log(articleDetails)
})

2. Do not handle error messages

I often write only the code logic for successful requests but ignore the failure of requests.

// ❌
const getUserInfo = async () => {
try {
const userInfo = await fetch('/api/getUserInfo')
} catch (err) {

}
}

This is inexperienced and we should give a user-friendly prompt instead of doing nothing.

// ✅
const getUserInfo = async () => {
try {
const userInfo = await fetch('/api/getUserInfo')
} catch (err) {
Toast(err.message)
}
}

--

--

fatfish

Hi friends, I am a front-end engineer from Alibaba, let’s code happily together.