Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write clean JavaScript code

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to write clean JavaScript code, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

1. Variable

Use a meaningful name

The names of variables should be descriptive, meaningful, and JavaScript variables should be named in hump case (camelCase).

/ / Don't ❌ const foo = "JDoe@example.com"; const bar = "John"; const age = 23th Const qux = true;// Do ✅ const email = "John@example.com"; const firstName = "John"; const age = 23th Const isActive = true

Boolean variables usually need to answer specific questions, such as:

IsActive

DidSubscribe

HasLinkedAccount

Avoid adding unnecessary context

When the object or class already contains the naming of the context, do not add redundant contexts to the variable names.

/ / Don't ❌ const user = {userId: "296e2589-7b33-400a-b762-007b730c8e6d", userEmail: "JDoe@example.com", userFirstName: "John", userLastName: "Doe", userAge: 23,}; user.userId;// Do ✅ const user = {id: "296e2589-7b33-400a-b762-007b730c8e6d", email: "JDoe@example.com", firstName: "John", lastName: "Doe", age: 23,}; user.id Avoid hard-coded values

Be sure to declare a meaningful and searchable constant, rather than inserting a constant value directly. Global constants can be named in SCREAMING_SNAKE_CASE style.

/ / Don't ❌ setTimeout (clearSessionData, 900000); / / Do ✅ const SESSION_DURATION_MS = 15 * 60 * 1000 * setTimeout (clearSessionData, SESSION_DURATION_MS); 2. Function

Use a meaningful name

The function name needs to describe the actual function of the function, even if it is very long. Function names usually use verbs, but functions that return Boolean values may be an exception-it can take the form of a yes or no question, and the function name should be humped.

/ / Don't ❌ function toggle () {/ /...} function agreed (user) {/ /...} / / Do ✅ function toggleThemeSwitcher () {/ /...} function didAgreeToAllTerms (user) {/ /...} use default parameters

The default parameter is cleaner than & & | or using additional conditional statements in the body of the function.

/ / Don't ❌ function printAllFilesInDirectory (dir) {const directory = dir | | ". /.} / / Do ✅ function printAllFilesInDirectory (dir =". /) {/ /.} limit the number of parameters

Although this rule may be controversial, it is best for a function to have less than three parameters. If there are more parameters, it may be one of the following two situations:

This function does too much and should be split.

The data passed to the function is related in some way and can be passed as a dedicated data structure.

/ / Don't ❌ function sendPushNotification (title, message, image, isSilent, delayMs) {/ /...} sendPushNotification ("New Message", "...", "http://...", false, 1000) / / Do ✅ function sendPushNotification ({title, message, image, isSilent, delayMs}) {/ /...} const notificationConfig = {title: "New Message", message: "...", image: "http://...", isSilent: false, delayMs: 1000,}; sendPushNotification (notificationConfig); avoid doing too much in one function

A function should do one thing at a time, which helps reduce the size and complexity of the function and make testing, debugging, and refactoring easier.

/ Don't ❌ function pingUsers (users) {users.forEach ((user) = > {const userRecord = database.lookup (user); if (! userRecord.isActive ()) {ping (user);}});} / / Do ✅ function pingInactiveUsers (users) {users.filter (! isUserActive) .forEach (ping);} function isUserActive (user) {const userRecord = database.lookup (user); return userRecord.isActive (); avoid using Boolean flags as parameters

The argument that the function contains a Boolean flag means that the function can be simplified.

/ / Don't ❌ function createFile (name, isPublic) {if (isPublic) {fs.create (`. / public/$ {name}`);} else {fs.create (name);} / Do ✅ function createFile (name) {fs.create (name);} function createPublicFile (name) {createFile (`. / public/$ {name}`);} avoid writing duplicate code

If you write repetitive code, you need to change multiple locations every time there is a logic change.

/ / Don't ❌ function renderCarsList (cars) {cars.forEach ((car) = > {const price = car.getPrice (); const make = car.getMake (); const brand = car.getBrand (); const nbOfDoors = car.getNbOfDoors (); render ({price, make, brand, nbOfDoors});} function renderMotorcyclesList (motorcycles) {motorcycles.forEach ((motorcycle) = > {const price = motorcycle.getPrice (); const make = motorcycle.getMake ()) Const brand = motorcycle.getBrand (); const seatHeight = motorcycle.getSeatHeight (); render ({price, make, brand, nbOfDoors});} / / Do ✅ function renderVehiclesList (vehicles) {vehicles.forEach ((vehicle) = > {const price = vehicle.getPrice (); const make = vehicle.getMake (); const brand = vehicle.getBrand (); const data = {price, make, brand} Switch (vehicle.type) {case "car": data.nbOfDoors = vehicle.getNbOfDoors (); break; case "motorcycle": data.seatHeight = vehicle.getSeatHeight (); break;} render (data);});} avoid side effects

In JavaScript, you should prefer functional mode to imperative mode. In other words, we should keep the function pure in most cases. Side effects can modify shared state and resources, leading to some strange problems. All side effects should be managed centrally, for example, if you need to change global variables or modify files, you can write a special util to do this.

/ / Don't ❌ let date = "21-8-2021"; function splitIntoDayMonthYear () {date = date.split ("-");} splitIntoDayMonthYear (); / / Another function could be expecting date as a stringconsole.log (date); / / ['21','8', '2021']; / / Do ✅ function splitIntoDayMonthYear (date) {return date.split ("-");} const date = "21-8-2021"; const newDate = splitIntoDayMonthYear (date); / / Original vlaue is intactconsole.log (date) / /'21-8-2021 console console.log (newDate); / / ['21','8', '2021'

In addition, if you pass a variable value to the function, you should directly clone the return of a new value instead of changing it directly.

/ / Don't ❌ function enrollStudentInCourse (course, student) {course.push ({student, enrollmentDate: Date.now ()});} / / Do ✅ function enrollStudentInCourse (course, student) {return [. Course, {student, enrollmentDate: Date.now ()}];} 3. Conditional statement

Use non-negative conditions

/ / Don't ❌ function isUserNotVerified (user) {/ /...} if (! isUserNotVerified (user)) {/ /...} / / Do ✅ function isUserVerified (user) {/ /...} if (isUserVerified (user)) {/ /..} use abbreviations whenever possible

/ / Don't ❌ if (isActive = true) {/ /...} if (firstName! = "& & firstName! = = null & & firstName! = = undefined) {/ /...} const isUserEligible = user.isVerified () & & user.didSubscribe ()? True: false;// Do ✅ if (isActive) {/ /...} if (!! firstName) {/ /...} const isUserEligible = user.isVerified () & & user.didSubscribe (); avoid too many branches

Early return will make your code linear, more readable, and less complex.

/ / Don't ❌ function addUserService (db, user) {if (! db) {if (! db.isConnected ()) {if (! user) {return db.insert ("users", user);} else {throw new Error ("No user");}} else {throw new Error ("No database connection");}} else {throw new Error ("No database") } / / Do ✅ function addUserService (db, user) {if (! db) throw new Error ("No database"); if (! db.isConnected ()) throw new Error ("No database connection"); if (! user) throw new Error ("No user"); return db.insert ("users", user);} use map rather than switch statement first

It can not only reduce complexity but also improve performance.

/ / Don't ❌ const getColorByStatus = (status) = > {switch (status) {case "success": return "green"; case "failure": return "red"; case "warning": return "yellow"; case "loading": default: return "blue";}; / / Do ✅ const statusColors = {success: "green", failure: "red", warning: "yellow", loading: "blue",} Const getColorByStatus = (status) = > statusColors [status] | | "blue"

Use optional links

Const user = {email: "JDoe@example.com", billing: {iban: "...", swift: "...", address: {street: "Some Street Name", state: "CA",}; / / Don't ❌ const email = (user & & user.email) | | Nswift A " Const street = (user & & user.billing & & user.billing.address & & user.billing.address.street) | | "const state A"; const state = (user & & user.billing & & user.billing.address & & user.billing.address.state) | | "Do A"; / / Do Do const email = user?.email? "NCMA"; const street = user?.billing?.address?.street? "NCMA"; const street = user?.billing?.address?.state? "Nbig A"; 4. Concurrence

Avoid callback

Callbacks are confusing and can lead to code being deeply nested, using Promise instead of callbacks.

/ / Don't ❌ getUser (function (err, user) {getProfile (user, function (err, profile) {getAccount (profile, function (err, account) {getReports (account, function (err, reports) {sendStatistics (reports, function (err) {console.error (err);}) / / Do ✅ getUser () .then (getProfile) .then (getAccount) .then (sendStatistics) .catch ((err) = > console.error (err)); / / or using Async/Await ✅✅ async function sendUserStatistics () {try {const user = await getUser (); const profile = await getProfile (user); const account = await getAccount (profile); const reports = await getReports (account); return sendStatistics (reports) } catch (e) {console.error (err);}} 5. Error handling

Handling thrown errors and reject's promise

/ Don't ❌ try {/ / Possible erronous code} catch (e) {console.log (e);} / Do ✅ try {/ / Possible erronous code} catch (e) {/ / Follow the most applicable (or all): / / 1-More suitable than console.log console.error (e); / / 2-Notify user if applicable alertUserOfError (e); / / 3-Report to server reportErrorToServer (e); / / 4-Use a custom error handler throw new CustomError (e);} 6. Annotation

Annotate only business logic

Readable code keeps you from over-commenting, so you should only annotate complex logic.

/ / Don't ❌ function generateHash (str) {/ / Hash variable let hash = 0; / / Get the length of the string let length = str.length; / / If the string is empty return if (! length) {return hash;} / / Loop through every character in the string for (let I = 0; I < length; iTunes +) {/ / Get character code. Const char = str.charCodeAt (I); / / Make the hash hash = (hash

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report